文件创建但不能写入其中
我的程序:检查Settings.txt文件。 如果文件不存在,请创建文本并自动写入。 如果Settings.txt文件已存在,请忽略。 不要在现有文件中创建或写入。
我的问题:当文件不存在时,Settings.txt文件会创建,但它是空的。 我希望程序在创建文件时写入它。 谢谢你的帮助。
private void Form1_Load(object sender, EventArgs e) { string path = @"C:\Users\Smith\Documents\Visual Studio 2010\Projects\Ver.2\Settings.txt"; if (!File.Exists(path)) { File.Create(path); TextWriter tw = new StreamWriter(path); tw.WriteLine("Manual Numbers="); tw.WriteLine(""); tw.WriteLine("Installation Technical Manual: "); tw.WriteLine("Performance Manual: "); tw.WriteLine("Planned Maintenance Technical Manual: "); tw.WriteLine("Service Calibration Manual: "); tw.WriteLine("System Information Manual: "); tw.WriteLine(""); tw.Close(); } }
这就是我认为发生的事情。 当我复制并运行你的代码时,抛出了一个exception。 这可能是因为您创建了两次文件,并且在第二次创建文件之前不要关闭它。
供参考, TextWriter tw = new StreamWriter(path);
为您创建文件。 您不需要调用File.Create
在后续运行期间,我认为你没有删除该文件,并且因为该文件已经存在,所以if (!File.Exists(path))
将永远不会被满足,并且将跳过整个if
语句
所以这里有多个要点
- 摆脱那个
File.Create
调用 - 如果你想要覆盖文件,你不应该检查它是否存在,你应该只是覆盖。
试试这个:
using(FileStream stream = File.Create(path)) { TextWriter tw = new StreamWriter(stream); tw.WriteLine("Manual Numbers="); tw.WriteLine(""); tw.WriteLine("Installation Technical Manual: "); tw.WriteLine("Performance Manual: "); tw.WriteLine("Planned Maintenance Technical Manual: "); tw.WriteLine("Service Calibration Manual: "); tw.WriteLine("System Information Manual: "); tw.WriteLine(""); }
即使在写入过程中发生exception, 使用也可确保文件流被关闭(处理)。
问题是File.Create返回一个FileStream,因此它使文件保持打开状态。 您需要将TextStream与TextWriter一起使用。 您还需要在using(…)语句中写入FileStream,或者在FileStream上手动调用Dispose(),以确保在处理完文件后关闭该文件。
虽然我在相当一段时间后回答,但我想我应该回答
using (TextWriter tw = new StreamWriter(path)) { StringBuilder sb = new StringBuilder(); sb.Append("Manual Numbers="); sb.Append(Environment.NewLine); sb.Append("Installation Technical Manual: "); sb.Append("Performance Manual: "); sb.Append("Planned Maintenance Technical Manual: "); sb.Append("Service Calibration Manual: "); sb.Append("System Information Manual: "); sb.Append(Environment.NewLine); tw.Write(sb.ToString()); }