[英]C# Print to a text file from a windows form
我能够获得此代码以在控制台应用程序中工作,但当前正在Windows窗体中工作。 我将输出更改为控制台应用程序,但这仍然无法正常工作。
string path = @"C:\Users\rbc658\Trajectory.txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter txt = new StreamWriter(path);
txt.WriteLine("Hello");
txt.Close();
}
else if (File.Exists(path))
{
using (var txt = new StreamWriter(path, true))
{
txt.WriteLine("Hello");
txt.Close();
}
}
“关闭”,“创建”和“写行”未像上面的文本中突出显示。 我正在使用system.io。 表单和控制台应用程序有什么不同之处会阻止其工作?
对于您来说,创建一个函数来向文本文件中写入内容的调用更为优雅
下面的代码为我工作:
private void Form1_Load(object sender, EventArgs e) // for example run this code when form loads
{
string path = @"C:\Users\Luka\Desktop\Trajectory.txt"; // your path to a text file
string text = "Hello"; // some text to write to a text file
Write(text, path, File.Exists(path)); // we are passing File.Exists(path) as a boolean to see wether or not to append text to a file
}
private void Write(string text, string path, bool file_exists)
{
//if File.Exists(path) is true, streamwriters second argument is true, so it appends
//else the argument is false and it does not append
StreamWriter txt = new StreamWriter(path, file_exists); // creates new object type StreamWriter with 2 arguments
//1. path to a file
//2. boolean to see wether or not to append the text to a file
txt.WriteLine(text); // writes text line to a file
txt.Dispose(); // disposes streamwriter
}
所有解释都显示为代码中的注释,因此您可以在测试程序时将其复制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.