4

我的程序:检查 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();
        }
    }
4

4 回答 4

14

尝试这个:

    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("");
    }

即使在写入过程中发生异常,using也可确保关闭(处置)文件流。

于 2013-08-27T20:44:12.957 回答
8

问题是 File.Create 返回一个 FileStream 所以它使文件保持打开状态。您需要将该 FileStream 与您的 TextWriter 一起使用。您还需要在 using(...) 语句中包装 FileStream 或在 FileStream 上手动调用 Dispose() ,以便确保在处理完文件后关闭文件。

于 2013-08-27T20:44:31.363 回答
6

这就是我认为发生的事情。当我复制并运行您的代码时,引发了异常。这可能是因为您创建了两次文件,并且在第二次创建之前没有关闭它。

作为参考,TextWriter tw = new StreamWriter(path);为您创建文件。你不需要打电话File.Create

在随后的运行中,我认为您不会删除该文件,并且由于该文件已经存在,if (!File.Exists(path))因此永远不会满足,并且if将跳过整个语句

所以这里有多个点

  • 摆脱那个File.Create电话
  • 如果你希望文件被覆盖,你不应该检查它是否存在,你应该覆盖。
于 2013-08-27T20:50:37.827 回答
2

虽然我在很长一段时间后才回答,但我想我应该回答

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());
 }
于 2013-08-28T15:17:37.983 回答