c#CSV文本文件到单个字符串(或数组或列表),然后添加或更改每个字符串并输出到单个字符串变量

本文关键字:字符串 单个 串并 变量 输出 添加 字符 文件 文本 数组 列表 | 更新日期: 2023-09-27 18:29:18

我使用具有多行(可能因用户输入而异)的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#CSV文本文件到单个字符串(或数组或列表),然后添加或更改每个字符串并输出到单个字符串变量

我在这里为您编写了一些混乱的逻辑,请检查并更正我的假设是否错误。

 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();

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
    }

我想你需要这样的东西:

    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();
        }