-1

我正在尝试写回 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;
}
4

2 回答 2

2

简单的这个

//Convert your list to csv string
string toWrite = string.Join(",",lines );
File.WriteAllText(YourFilePath, toWrite);
于 2013-07-25T19:23:10.587 回答
0

您正在使用 aStreamReader从文件中读取。使用 aStreamWriter写回它。这段代码应该这样做

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. 您要替换原始文件

编辑:或者,您可以将整个内容重写为:

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());
于 2013-07-25T19:28:08.927 回答