编程语言
首页 > 编程语言> > C#.net从.bat文件的结果填充数据网格

C#.net从.bat文件的结果填充数据网格

作者:互联网

我创建了一个.bat文件,该文件显示了Windows终端服务中登录的所有用户.
我可以在后面的C#代码中执行.bat文件,并在标签或文本框中以纯文本形式显示结果.我想做的是数据将用户名和会话ID绑定到数据网格中.

  protected void Button1_Click(object sender, EventArgs e)
{
    System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(@"C:\listfiles.bat");
    psi.RedirectStandardOutput = true;
    psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    psi.UseShellExecute = false;
    System.Diagnostics.Process listFiles;
    listFiles = System.Diagnostics.Process.Start(psi);
    System.IO.StreamReader myOutput = listFiles.StandardOutput;
    listFiles.WaitForExit(2000);
     if (listFiles.HasExited)
       {
        string output = myOutput.ReadToEnd();
        // this.TextBox1.Text = output;
        }

  }

解决方法:

您可以尝试这样的事情:

        string[] input = myOutput.ReadToEnd().Split('\n');

        DataTable table = new DataTable();

        table.Columns.Add(new DataColumn("UserName", typeof(string)));
        table.Columns.Add(new DataColumn("SessionId", typeof(string)));

        foreach (string item in input)
        {
            DataRow row = table.NewRow();
            row[0] = item.Split(',')[0];
            row[1] = item.Split(',')[1];
            table.Rows.Add(row);
        }

        myGridView.DataSource = table;

        // for WebForms:
        myGridView.DataBind();

当然,您需要:

>做一些错误检查(我在示例中做了很多假设)
>确保用户名在会话ID之前
>还请确保您有要绑定到的DataGrid(myGridView)
>检查您的输出确实是换行符和逗号分隔
>如果没有,则更新代码中的字符
>另外…我故意降低了效率,以显示流程

标签:data-binding,datagrid,c,batch-file
来源: https://codeday.me/bug/20191209/2097512.html