Claudi Claudi - 4 years ago 95
C# Question

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.

Answer Source

You don't need to open the file stream yourself. File.WriteAllText() does all this for you. 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().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download