将进程输出存储在数组中

时间:2018-03-08 14:53:36

标签: c# .net

我发起了一个空阵列。

 string[] line = new string[] { };

我想存储下面将使用while循环在cmd处理中输出的每一行。如果我将值存储在字符串变量中,这似乎很容易。

如下图所示:

while (!proc.StandardOutput.EndOfStream)
{
    line = proc.StandardOutput.ReadLine();
}

但是,我不确定如何将值存储为数组中的单独元素。我试过了:

while (!proc.StandardOutput.EndOfStream)
{
    for(a in line)
    {
        a = proc.StandardOutput.ReadLine();
    }
}

但它不起作用。

这可能是一个非常基本的问题。但我还在学习C#。

2 个答案:

答案 0 :(得分:5)

解决方案很少。一种方法是使用List<string>代替string[]

List<string> line = new List<string>();

然后再添加一行:

while (!proc.StandardOutput.EndOfStream)
{
    line.Add(proc.StandardOutput.ReadLine());
}

答案 1 :(得分:1)

数组在索引的基础上工作。因此,如果你想使用一个数组,你需要指定它需要多长时间,换句话说,它可以包含多少项:

// this array can store 100 items
string[] line = new string[100];

要访问某个位置,您需要使用[ ] operator并在数组中向前移动,您需要一个类型为int的索引变量,您可以增加每次迭代

int indexer = 0;

while (!proc.StandardOutput.EndOfStream)
{
    line[indexer] = proc.StandardOutput.ReadLine();
    indexer ++; // increment
}

这样您需要提前知道要在阵列中存放多少项目。

另一种方法是使用像List这样可以动态增长的灵活集合。旁注:索引与同一[ ]运算符一起使用,但通过Add方法添加项目

如果您想了解更多,请查看此overview of possible collection types

相关问题