C#,windows窗体,StremWriter,标题行



我正试图在运行的csv文件日志中添加一个标头。这就是我想要的,

项目名称、项目序列号、项目构建<除非文件被删除,否则永远不会更改的第一行。在这种情况下,创建一个新的标题行。

在那一行之后,我希望每次都将数据添加到下一行。

这是我迄今为止所拥有的。

//写入CSV字符串路径=if(!File.Exists(路径(({File.CreateText(路径(;

}
string projectName = ProjectName_TextBox.Text;
string projetcBuild = ProjectBuild_TextBox.Text;
string projectSN = SN_TextBox.Text;
string header = "Project Name, Project Build, Project SNn";

using (StreamWriter sw = new StreamWriter(path, true)) // true for appending data to file, false to overwrite in file
{

sw.WriteLine(header);


sw.WriteLine(string.Format(projectName + "," + projetcBuild.ToString() + "," + projectSN.ToString()));


}

它的作用是每次单击按钮时都添加标题和数据。我只想将头添加到文件中一次。只有表单中的数据才会被附加到下一行,我想我已经有了。请帮忙。

File.CreateText会返回一个streamwriter;你可以使用它,也可以借此机会写标题


string header = "Project Name, Project Build, Project SNn";
// Write to CSV string path
try{
StreamWriter sw;
if (!File.Exists(path)) {
sw = File.CreateText(path);
sw.WriteLine(header);
} else
sw = File.AppendText(path);
string projectName = ProjectName_TextBox.Text;
string projetcBuild = ProjectBuild_TextBox.Text;
string projectSN = SN_TextBox.Text;

sw.WriteLine(projectName + "," + projetcBuild + "," + projectSN);

}
finally{
sw.Dispose(); 
}

您不需要对字符串调用ToString。您不需要对没有占位符的字符串调用format。你不应该真的麻烦写你自己的csv编写器;有这么多好的库可以做到这一点。只要有人在的一个文本框中放一个逗号,这个简单的实现就会失败

在使用file.exists(路径(添加标头之前,可以检查文件是否存在

string projectName = ProjectName_TextBox.Text;
string projetcBuild = ProjectBuild_TextBox.Text;
string projectSN = SN_TextBox.Text;
string header = "Project Name, Project Build, Project SNn";
var firstWrite = !File.Exists(path);
using (StreamWriter sw = new StreamWriter(path, true)) // true for appending data to file, false to overwrite in file
{
if(firstWrite)
sw.WriteLine(header);


sw.WriteLine(string.Format(projectName + "," + projetcBuild.ToString() + "," + projectSN.ToString()));

最新更新