C# 在 CSV 文件中编辑/保存一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14370757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:37:54  来源:igfitidea点击:

Editing/Saving a row in a CSV file

c#asp.netcsv

提问by KJSR

After following this topicI am able to create the new row but my question is how do I save or write the new line to the file?

遵循本主题后,我可以创建新行,但我的问题是如何将新行保存或写入文件?

I tried 'StreamWriter' but it only writes the newly created line.

我试过 'StreamWriter' 但它只写新创建的行。

Any suggestions please?

请问有什么建议吗?

Here is my code so far:

到目前为止,这是我的代码:

string path = @"C:/CSV.txt";

string[] lines = File.ReadAllLines(path);

var splitlines = lines.Select(l => l.Split(','));

foreach (var line in splitlines)
{
   if(line[1].Contains("34"))
   {                                        
     line[1] = "100";
     var newline = string.Join(",", line);
     StreamWriter sr = new StreamWriter(path);    
     sr.WriteLine(newline);
     sr.Close();                                      
   }
 }

采纳答案by Tommaso Belluzzo

Here is your solution using StreamReaderclass:

这是您使用StreamReader类的解决方案:

String path = @"C:\CSV.txt";
List<String> lines = new List<String>();

if (File.Exists(path));
{
    using (StreamReader reader = new StreamReader(path))
    {
        String line;

        while ((line = reader.ReadLine()) != null)
        {
            if (line.Contains(","))
            {
                String[] split = line.Split(',');

                if (split[1].Contains("34"))
                {
                    split[1] = "100";
                    line = String.Join(",", split);
                }
            }

            lines.Add(line);
        }
    }

    using (StreamWriter writer = new StreamWriter(path, false))
    {
        foreach (String line in lines)
            writer.WriteLine(line);
    }
}

If you want to overwrite the file, use thisStreamWriter constructor with append = false.

如果要覆盖文件,请将此StreamWriter 构造函数与append = false.

回答by sa_ddam213

Maybe somthing like this, you probably will need to clean it up and add some error handling, but it does the job

也许像这样,你可能需要清理它并添加一些错误处理,但它可以完成工作

    string path = @"C:\CSV.txt";

    string[] lines = File.ReadAllLines(path);
    for (int i = 0; i < lines.Length; i++)
    {
        string line = lines[i];
        if (line.Contains(","))
        {
            var split = line.Split(',');
            if (split[1].Contains("34"))
            {
                split[1] = "100";
                line = string.Join(",", split);
            }
        }
    }
    File.WriteAllLines(@"C:\CSV.txt", lines);

回答by Rajenthiran T

        string str;
        string PID;
        string PN;
        string UP;
        string DIS;
        string STK;
        string CSVFilePathName = @"C:\admin.csv";
        string[] Lines = File.ReadAllLines(CSVFilePathName);
        File.Delete(CSVFilePathName);
        StreamWriter sw = new StreamWriter(CSVFilePathName", true);

            PID = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[0].Controls[0])).Text;
            PN = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text;
            UP = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text;
            DIS = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text;
            STK = ((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text;
        foreach (string li in Lines)
        {
            string[] Fields = li.Split(',');
            if(PID==Fields[0])
            {                                                                     
                str = PID + "," + PN + "," + UP + "," + DIS + "," + STK;                                 
            }
            else
            {
                str = Fields[0] + "," + Fields[1] + "," + Fields[2] + "," + Fields[3] + "," + Fields[4];                 
            }
            sw.WriteLine(str);
        }
        sw.Flush();
        sw.Close();