【问题标题】:C#.net Populate a datagrid from the result of a .bat fileC#.net 从 .bat 文件的结果填充数据网格
【发布时间】:2010-07-30 16:38:34
【问题描述】:

我创建了一个 .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;
        }

  }

【问题讨论】:

    标签: c# datagrid data-binding batch-file


    【解决方案1】:

    你可以试试这样的:

            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)
    • 检查您的输出确实是换行符和逗号分隔
    • 如果不是,则更新代码中的字符
    • 另外...我故意降低了效率以显示该过程

    【讨论】:

    • 我需要 dataBind() 输出。
    • 行 myGridView.DataSource = table;应该为你做。如果不是单独发生,您可能必须在该行之后立即调用 myGridView.BindData(或 DataBind)。 (我假设是 WinForms,但从您过去的 Qs 来看,您可能在 ASP.NET 中 - 在这种情况下,您确实需要显式调用 BindData 方法。)
    【解决方案2】:

    与其依赖运行 .bat 文件,不如直接使用远程桌面服务 API 之类的东西来完成?

    http://msdn.microsoft.com/en-us/library/aa383459%28VS.85%29.aspx

    或者也许使用 Wmi:

    http://gallery.technet.microsoft.com/ScriptCenter/en-us/f053de86-f053-474b-9b21-f2e6b161948f

    【讨论】:

    【解决方案3】:

    您可以在内存中创建一个 DataTable,为 username 和 sessionid 添加列。 在您的循环中,根据分隔字符(逗号?分号?) split() 输出字符串,并基于此向表中添加行。

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

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-16
        • 1970-01-01
        • 2020-11-17
        相关资源
        最近更新 更多