如何写回CSV文件

时间:2013-07-25 19:18:43

标签: c# c#-4.0 c#-3.0

我正在尝试回写CSV文件,如何更改此脚本以写回CSV文件,我是C#的新手?请帮帮我

public void Main()
{

    List<String> lines = new List<string>();
    string line;
    System.IO.StreamReader file = new System.IO.StreamReader("C:\\NewFolder\\Test.csv");

    while ((line = file.ReadLine()) != null)
    {

        lines.Add(line);
    }

    lines.RemoveAll(l => l.Contains(",,,,,"));

    using (System.IO.StreamWriter writer = new System.IO.StreamWriter("C:\\NewFolder\\Test.csv", false))
    {
        for (int i = 0; i < lines.Count; i++)
        {
            writer.WriteLine(lines[i]);
        }
    }


    Dts.TaskResult = (int)ScriptResults.Success;
}

2 个答案:

答案 0 :(得分:2)

只需

//Convert your list to csv string
string toWrite = string.Join(",",lines );
File.WriteAllText(YourFilePath, toWrite);

答案 1 :(得分:0)

您正在使用StreamReader来读取文件。使用StreamWriter回写它。这段代码应该这样做

using (System.IO.StreamWriter writer = new System.IO.StreamWriter("c:\\test.txt", false))
{
    for (int i = 0; i < lines.Count; i++)
    {
        writer.WriteLine(lines[i]);
    }
}

注意这假设有两件事:

  1. 您已关闭阅读器
  2. 您想要替换原始文件
  3. 编辑:或者你可以改写整个事情:

    string fileName = "C:\\NewFolder\\Test.csv";
    List<string> lines = System.IO.File.ReadAllLines(fileName).ToList();
    lines.RemoveAll(l => l.Contains(",,,,,"));
    System.IO.File.WriteAllLines(fileName, lines.ToArray());