【问题标题】:C# Splitting string lines into multiple stringsC#将字符串行拆分为多个字符串
【发布时间】:2015-06-05 14:02:42
【问题描述】:

我正在尝试弄清楚如何将一些 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# 中做一些基本的事情,但这超出了我的想象:I

【问题讨论】:

  • 您尝试使用String.Split 吗?还是Regex?
  • String.Split 如果某些单元格有空格(如“SAMSUNG SSD 830 系列”),则会出现问题。
  • 这里不会拆分字符串,因为有空格我不知道怎么解决。
  • 您可以直接在 c# 中查询 WMI,而不是向外部应用程序获取 WMI 信息。然后您可以直接访问每个数据字段,而无需拆分任何字符串。 C# 中的 WMI 查询是收集有关系统信息的 SQL 查询。例如:var allPDisks = Session.QueryInstances(@"root\microsoft\windows\storage", "WQL", "SELECT * FROM MSFT_PhysicalDisk") MSFT_PhysicalDisk 类提供了您尝试获取的所有字段。见this link
  • 你需要从事实开始:总会有4列,第一列和最后一列永远是数字;尝试从那里向后工作以解析剩余的列,然后您可以构建您的列表。

标签: c# arrays string list text


【解决方案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 列,第一列和最后一列始终是数字,并从那里建立。

【讨论】:

    【解决方案2】:

    您运行的命令似乎确保了每列之间的双空格。然后只对双字符串进行字符串拆分。

    所以,给定你的字符串 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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-14
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 2018-04-18
      相关资源
      最近更新 更多