C# 如何编辑文件,在开始时添加数据,而不重写整个文件?
我有一个csv文件,我需要根据文件的前两个字符添加一个唯一的ID。我有以下代码:C# 如何编辑文件,在开始时添加数据,而不重写整个文件?,c#,C#,我有一个csv文件,我需要根据文件的前两个字符添加一个唯一的ID。我有以下代码: using (StreamReader sr = new StreamReader(f)) { string currentLine; int id = 0; while ((currentLine = sr.ReadLine())
using (StreamReader sr = new StreamReader(f))
{
string currentLine;
int id = 0;
while ((currentLine = sr.ReadLine()) != null)
{
string row = currentLine.ToString();
string FirstTwoCharacters = currentLine.Substring(0, 2);
if (FirstTwoCharacters == "01")
{
id = id + 1;
row += "*" + id.ToString();
using (StreamWriter files = File.AppendText(dir + newfilename))
{
files.WriteLine(row);
}
}
else
{
row += "*" + id.ToString();
using (StreamWriter files = File.AppendText(dir + newfilename))
{
files.WriteLine(row);
}
}
}
}
csv文件可以是巨大的,1Gb大小,大约600万行。只是需要建议,如果有更快的方法来处理此问题,因为当前处理一个文件可能需要3个多小时,并且可以一次接收多个文件。您可以保持stream writer打开,而不是打开新文件为每行输入文件追加行:
using (StreamReader sr = new StreamReader(f))
using (StreamWriter files = File.AppendText(dir + newfilename))
{
string currentLine;
int id = 0;
while ((currentLine = sr.ReadLine()) != null)
{
string firstTwoCharacters = currentLine.Substring(0, 2);
if (firstTwoCharacters == "01")
id++;
files.WriteLine(currentLine + "*" + id);
}
}
您还可以使用File.ReadLines
枚举源代码行:
using (StreamWriter writer = File.AppendText(dir + newfilename))
{
int id = 0;
foreach(var line in File.ReadLines(f))
{
if (line.Substring(0,2) == "01")
id++;
writer.WriteLine($"{line}*{id}");
}
}
甚至LINQ方法
int id = 0;
var newLines = from line in File.ReadLines(f)
let incrementId = line.Substring(0,2) == "01"
select $"{line}*{incrementId ? (++id) : id}";
File.WriteAllLines(dir + newfilename, newLines);
在循环中打开(文件.AppendText
)需要花费大量时间,请将其移到循环之外
using (StreamReader sr = new StreamReader(f))
{
string currentLine;
int id = 0;
using (StreamWriter files = File.AppendText(dir + newfilename))
{
while ((currentLine = sr.ReadLine()) != null)
{
string row = currentLine.ToString();
string FirstTwoCharacters = currentLine.Substring(0, 2);
if (FirstTwoCharacters == "01")
{
id = id + 1;
row += "*" + id.ToString();
files.WriteLine(row);
}
else
{
row += "*" + id.ToString();
files.WriteLine(row);
}
}
}
}
分块数据,而不是为每行写入文件。这是非常大的开销。string row=currentLine.ToString();。。。字符串到字符串?字符串到字符串,绝对确定,或者只是一些坏代码…由你决定。那将是坏代码。从文档中可以看出:“因为这个方法只是简单地返回当前字符串,不需要直接调用它”…这是一个笑话。这是我在代码中的错误,因为我对代码进行了一些修改,并将其保留了下来。这确实是一个糟糕的代码。这让我很清楚,这是一个需要记住的代码。非常感谢。