【问题标题】:c# CSV text file to single string (or array or list ) then add to or alter each string and output to single string variablec# CSV 文本文件到单个字符串(或数组或列表),然后添加或更改每个字符串并输出到单个字符串变量
【发布时间】:2016-01-07 14:14:59
【问题描述】:

我正在使用具有多行的 C# DataGridView(可能因用户输入而异)导出到纯文本文件,结果如下:

CompName,PowerOn,thin,Storage,acceptLic,verify,SSL,c:\test\myfile.img,root,P@ssw0rd,192.168.1.100
CompName,PowerOn,thin,Storage,acceptLic,verify,SSL,c:\test\myfile.img,root,P@ssw0rd,192.168.1.100
CompName,PowerOn,thin,Storage,acceptLic,verify,SSL,c:\test\myfile.img,root,P@ssw0rd,192.168.1.100

//...and more lines if user adds more

我想做的是解析文件并将每一行加载到一个变量中,我想将其附加到命令行可执行文件中,例如:

"C:\Program Files\Mytest\Mytest Tool\mytest.exe" -n=CompName --powerOn -dmode=convert -volume=storage1 --acceptLicense --noVerification --SSL c:\Users\me\Documents\down\myfile.img system1://root:myPassword@192.168.1.151

所以问题是这是怎么做到的?

我检查了许多示例,现在对于使用哪种方法来产生所需结果开始变得相当混乱。 (StreamReader、StringSplit、StringJoin 等等..)

我能够获取文件的内容以使用以下方法构建列表:

List<string> list = new List<string>();
        using (StreamReader reader = new StreamReader(@"c:\foo\stest.txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                list.Add(line); // Add to list.
                Console.WriteLine(line); // Write to console.
                StringBuilder builder = new StringBuilder();

        //but where to from here ?


            }

我在她的正确轨道上吗?我会很感激任何答案..

谢谢你

【问题讨论】:

    标签: c# arrays string list


    【解决方案1】:

    我在这里给你写了一些乱七八糟的逻辑,如果我的假设是错误的,请检查并纠正。

     List<string> list = new List<string>();
            using (StreamReader reader = new StreamReader(@"C:\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\txt1.txt"))
            {
                string line;
                string[] parameters =  null;
                while ((line = reader.ReadLine()) != null)
                {
                    list.Add(line); // Add to list.
                    Console.WriteLine(line); // Write to console.
                    StringBuilder builder = new StringBuilder();
    
    
                    parameters = line.Split(',');
    
                    builder.Append("-n=");
                    int paramCount = 0;
                    foreach (var param in parameters)
                    {
                        if (paramCount == 0)
                        {
                            builder.Append(param + " ");
                        }
                        else if (paramCount == 2)
                        {
                            // your req seems you need static parameter here
                            // if my assumption is wrong, then correct your logic
                            builder.Append(string.Format("-dmode=convert "));
                        }
                        else if (paramCount == 3)
                        {
                            // your req seems you need static parameter here
                            // if my assumption is wrong, then correct your logic
                            builder.Append(string.Format("-volume=storage1 "));
                        }
                        else if(paramCount <= 5 )
                        {
                            builder.Append(string.Format("--{0} ", param));
                        }
                        else if (paramCount > 5)
                        {
                            //Correct the logic as per your requirement.                            
                            string sslParams = " --" + param + " ";
                            string[] sslParamvalues = parameters.Take(11).Skip(7).ToArray();
                             sslParams +=   string.Join(",", sslParamvalues);
                            builder.Append(string.Format("--{0} ", sslParams));
                        }
                        paramCount++;
                    }
                    Console.WriteLine(builder.ToString());
    
                    Process p = new Process();
                    p.StartInfo.FileName = @"C:\Program Files\Mytest\Mytest Tool\mytest.exe";
                    p.StartInfo.Arguments = string.Format(builder.ToString());
    
                    //p.Start();
    

    【讨论】:

    • .......哇,谢谢你......这个。正是我所需要的......哇,它直截了当:-)我只需要修复索引计数但是哇,我非常感谢你:-)你摇滚!
    【解决方案2】:

    Microsoft.VisualBasic.FileIO 命名空间中有一个名为TextFieldParser 的类,专门用于解析 CSV 数据。您可以使用它来解析文件中的数据。

    一些示例代码展示了它是如何使用的:

    using ( TextFieldParser csvReader = new TextFieldParser( fileName ) ) {
        csvReader.SetDelimiters( new string[] { "," } );
        csvReader.HasFieldsEnclosedInQuotes = true;
    
        MyType entry = null;
        while ( !csvReader.EndOfData ) {
            string[] fieldData = csvReader.ReadFields();
            // Code to build an entry or perform other actions goes here
        }
    

    【讨论】:

      【解决方案3】:

      我认为你需要这样的东西:

          private string Process()
          {
              // You dont need this list
              //List<string> list = new List<string>();
      
              using (System.IO.StreamReader reader = new System.IO.StreamReader(@"c:\foo\stest.txt"))
              {
                  string line;
      
                  StringBuilder builder = new StringBuilder();
      
                  do
                  {
                      line = reader.ReadLine();
                      if (line== null)
                          continue;
      
                      Console.WriteLine(line); // Write to console.
      
                      // Process line Here
                       //string[] values = line.Split(',');
                      //list.Add(line); // Add to list.
                      builder.AppendLine(line);
                  } while (!reader.EndOfStream);
      
                  return builder.ToString();
      
              }
          }
      

      要导出到文件只需使用

              string treated = Process();
              using (System.IO.StreamWriter writer = new System.IO.StreamWriter(@"c:\foo\stestTreated.txt", false, Encoding.Unicode))
              {
                  writer.Write(treated);
                  writer.Close();
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-04
        • 1970-01-01
        • 1970-01-01
        • 2011-12-11
        相关资源
        最近更新 更多