我有一个控制台应用程序
,我想在 CSV 文件中添加一个标题行
,而不将数据加载到应用程序中。我需要什么代码来做到这一点,但也只检查第一行以查看标题是否已经存在,如果不存在则不添加标题行?我已经尝试了几种方法来做到这一点,但找不到一种方法来编码这个而不加载整个文件以检查它是否存在然后添加标题行。
最佳答案
您可以使用 StreamReader
和 StreamWriter
来最小化内存使用量。
我的建议是逐行读取csv文件,如果需要加header,写入临时文件。在内存方面,它是高效的。
private void AddHeader(string filename)
{
string tempFilename = "temp.csv";
bool toCopy = false;
using (var sw = new StreamWriter(tempFilename, false))
{
//check if header exists
using(var sr = new StreamReader(filename))
{
var line = sr.ReadLine(); // first line
if(line != null && line != "Your Header") // check header exists
{
toCopy = true; // need copy temp file to your original csv
// write your header into the temp file
sw.WriteLine("Your Header");
while(line != null)
{
sw.WriteLine(line);
line = sr.ReadLine();
}
}
}
}
if(toCopy)
File.Copy(tempFilename, filename, true);
File.Delete(tempFilename);
}
关于c# - 如何在不加载整个文件的情况下将标题行添加到 CSV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43726825/