我试图弄清楚如何将一些cmd输出分成多个字符串,以后我可以用来设置标签。
我使用的代码是:
ProcessStartInfo diskdrive = new ProcessStartInfo("wmic", " diskdrive get index, model, interfacetype, size");
diskdrive.UseShellExecute = false;
diskdrive.RedirectStandardOutput = true;
diskdrive.CreateNoWindow = true;
var proc = Process.Start(diskdrive);
string s = proc.StandardOutput.ReadToEnd();
它提供如下输出:
Index InterfaceType Model Size
2 IDE WesternDigital 1000202273280
1 IDE Seagate 500105249280
0 IDE SAMSUNG SSD 830 Series 128034708480
是否可以将它放在列表或数组中,以便我可以获得例如磁盘2的大小,或磁盘0的接口类型。我可以在C#中做一些基本的事情,但这是我的头脑:我
答案 0 :(得分:1)
这是一个工作示例。 “结果”将包含一个包含您需要的相关部分的列表。这是第一次通过,我确信可以在某种程度上进行重构:
using System;
using System.Collections.Generic;
using System.Linq;
namespace columnmatch
{
internal class Program
{
private const string Ex1 = "2 IDE WesternDigital 1000202273280";
private const string Ex2 = "1 IDE Seagate 500105249280 ";
private const string Ex3 = "0 IDE SAMSUNG SSD 830 Series 128034708480";
private static void Main(string[] args)
{
var result = new List<MyModel>();
result.Add(ParseItem(Ex1));
result.Add(ParseItem(Ex2));
result.Add(ParseItem(Ex3));
}
private static MyModel ParseItem(string example)
{
var columnSplit = example.Split((char[]) null, StringSplitOptions.RemoveEmptyEntries);
int index = -1;
string interfaceType = string.Empty;
long size = -1;
string model = string.Empty;
if (columnSplit.Count() == 4)
{
//direct match (no spaces in input)
index = Convert.ToInt32(columnSplit[0]);
interfaceType = columnSplit[1];
model = columnSplit[2];
size = Convert.ToInt64(columnSplit[3]);
}
else
{
string modelDescription = string.Empty;
for (int i = 0; i < columnSplit.Count(); i++)
{
if (i == 0)
{
index = Convert.ToInt32(columnSplit[i]);
}
else if (i == 1)
{
interfaceType = columnSplit[i];
}
else if (i == columnSplit.Count() - 1) //last
{
size = Convert.ToInt64(columnSplit[i]);
}
else
{
//build the model
modelDescription += columnSplit[i] + ' ';
}
}
model = modelDescription.TrimEnd();
}
var myItem = BuildResultItem(index, interfaceType, model, size);
return myItem;
}
private static MyModel BuildResultItem(int index, string interfaceType, string model, long size)
{
var myItem = new MyModel
{
Index = index,
InterfaceType = interfaceType,
Model = model,
Size = size
};
return myItem;
}
private class MyModel
{
public int Index { get; set; }
public string InterfaceType { get; set; }
public string Model { get; set; }
public long Size { get; set; }
}
}
}
这个答案遵循我的评论中的事实:总会有4列,第一列和最后一列始终是数字,并从那里开始构建。
答案 1 :(得分:0)
您运行的命令似乎确保每列之间有一个双倍空格。然后就是在双字符串上进行字符串拆分的问题。
所以,鉴于你的字符串s
,这对我有用:
var map =
s
.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
.Skip(1)
.Select(x => x.Split(new [] { " " }, StringSplitOptions.RemoveEmptyEntries))
.Select(x => x.Select(y => y.Trim()).ToArray())
.ToDictionary(
x => int.Parse(x[0]),
x => new
{
InterfaceType = x[1],
Model = x[2],
Size = ulong.Parse(x[3]),
});
我可以这样做:
string it = map[0].InterfaceType;
ulong size = map[2].Size;