我正在尝试回写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;
}
答案 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]);
}
}
注意这假设有两件事:
编辑:或者你可以改写整个事情:
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());