2010-07-30 65 views
3

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

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; 
     } 

    } 

回答

2

你可以尝试这样的事:

 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)绑定到
  • 检查你的输出确实是换行和逗号分隔
  • 如果没有,那么在代码
  • 另外需要更新字符... ...我做故意的效率较低,从SO显示进程
+0

我需要dataBind()输出。 – djshortbus 2010-07-30 17:54:01

+0

该行myGridView.DataSource = table;应该为你做。如果它不是单独发生的,你可能需要在该行之后调用myGridView.BindData(或DataBind)。 (我假设WinForms,但从你过去的Qs来判断你可能在ASP.NET中 - 在这种情况下,你需要明确地调用BindData方法。) – 2010-07-30 18:36:50

0

您可以在内存中创建一个DataTable,为用户名和sessionid添加列。 在循环中,根据分隔字符(逗号?分号?)拆分()输出字符串,并根据该字符将行添加到表中。

然后将其设置为网格和数据绑定的数据源。

或者,您可以使用其他类型的集合。

0

您可以创建一个xml结构,然后将数据网格绑定到该结构。