创建一个Txt文件并写入它

时间:2017-07-24 09:25:43

标签: c# textbox text-files

我想创建一个文本文件,然后将TextBox的文本添加到其中。 使用以下代码创建文本文件时没有任何问题:

InitializeComponent();
string path = @"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
    File.Create(path);
}

但是当我尝试将文本添加到文本文件时,我收到错误信息正在使用该文件。如果文件在运行代码之前已经存在,则不会出现此错误,并且TextBox.Text已添加到文件中。 我使用此代码将文本添加到文本文件中:

public void writeTxt()
{
    string path = @"C:\Users\Morris\Desktop\test.txt";
    if (File.Exists(path))
    {
        using (var tw = new StreamWriter(path, true))
        {
            tw.WriteLine(TextBox1.Text);
            tw.Close();
        }
    }
}

你能帮助我吗?

6 个答案:

答案 0 :(得分:10)

您实际上不必检查文件是否存在,因为StreamWriter会为您执行此操作。

using (var tw = new StreamWriter(path, true))
{
    tw.WriteLine(TextBox1.Text);
}
  

public StreamWriter(            字符串路径,            布尔附加        )

     

确定是否将数据附加到文件。如果文件存在且append为false,则覆盖该文件。如果文件存在且append为true,则数据将附加到文件中。否则,将创建一个新文件。

答案 1 :(得分:2)

您应该File.Create使用using语句,因为它会在创建时锁定文件。所以只需更改此行:

File.Create(path);

对此:

using (File.Create(path));

答案 2 :(得分:0)

如果文件存在,则可以覆盖或附加。如果该文件不存在,则此构造函数将创建一个新文件。因此,您无需检查文件是否存在。

您需要确保文件已关闭,然后才能修改它。

答案 3 :(得分:0)

正如您所看到的,here, StreamWriter实际上会在指定的路径上创建一个不存在的文件,因此检查它是无用的。

我建议删除创建文件的部分,然后开始编写:

public void writeTxt()
{
    string path = @"C:\Users\Morris\Desktop\test.txt";
    using (var tw = new StreamWriter(path, true))
    {
        tw.WriteLine(TextBox1.Text);
        tw.Close();
    }
}

但如果你真的想事先创建文件,请记住FileStream调用创建的Dispose File.Create对象。 Dispose来电会自动为您致电FlushClose,因此它足够安全,您可以通过多种方式执行此操作:

InitializeComponent();
string path = @"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
    using ( File.Create(path) ) ; // This will generate warnings that you're not using the object and so on, but that's okay,
}

或者像这样:

InitializeComponent();
string path = @"C:\Users\Morris\Desktop\test.txt";
if (!File.Exists(path))
{
    FileStream fs = File.Create(path);
    fs.Dispose();
}

答案 4 :(得分:-1)

你需要移动你的

tw.Close();

在您使用之外。像这样:

public void writeTxt()
{
    string path = @"C:\Users\Morris\Desktop\test.txt";
    if (File.Exists(path))
    {
        using (var tw = new StreamWriter(path, true))
        {
            tw.WriteLine(TextBox1.Text);
        }
        tw.Close();
    }
}

编辑:正如所指出的,当使用结束时,编写者被处理掉,所以不需要手动关闭。

public void writeTxt()
{
    string path = @"C:\Users\Morris\Desktop\test.txt";
    if (File.Exists(path))
    {
        using (var tw = new StreamWriter(path, true))
        {
            tw.WriteLine(TextBox1.Text);
        }
    }
}

答案 5 :(得分:-2)

此问题之前已在此主题中得到解答。 Closing a file after File.Create

在再次使用之前,您需要关闭文件流。