简体   繁体   English

如何将文本框的内容保存到文件

[英]How to Save contents of a textbox to a file

I have looked around on several answers to similar questions, but somehow this isnt working for me. 我环顾了几个类似问题的答案,但是以某种方式这对我没有用。 I am trying to save the contents of a textbox into a user promptet file. 我正在尝试将文本框的内容保存到用户提示文件中。

private void btnSave_Click(object sender, EventArgs e)
{
    Stream myStream;
    SaveFileDialog saveFileDialog1 = new SaveFileDialog();

    saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
    saveFileDialog1.FilterIndex = 2;
    saveFileDialog1.RestoreDirectory = true;

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        if ((myStream = saveFileDialog1.OpenFile()) != null)
        {
            File.WriteAllText(saveFileDialog1.FileName, rtbIncoming.Text);
            myStream.Close();
        }
    }
}    

The User prompt pops up as expected, and the file is generated but without any content. 用户提示符会按预期方式弹出,并且已生成文件,但没有任何内容。

You don't need to open the file stream yourself. 您不需要自己打开文件流。 File.WriteAllText() does all this for you. File.WriteAllText()为您完成所有这些操作。 So this should be enough: 因此,这应该足够了:

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    File.WriteAllText(saveFileDialog1.FileName, rtbIncoming.Text);

I guess your code leads to an empty file because you open a seperate stream that isn't used to write and closed (and flushed) after the call to WriteAllText() . 我猜你的代码会导致一个空文件, 因为在调用WriteAllText() 之后 ,您打开了一个单独的流,该流不用于写入和关闭(并刷新WriteAllText()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM