0

I'm developing an application that has a TextBox. I want to write its contents to a file, but how can I do this?

jdehaan
  • 19,700
  • 6
  • 57
  • 97
Nathan Campos
  • 28,769
  • 59
  • 194
  • 300

4 Answers4

3

There are many ways to accomplish this, the simplest being:

 using(var stream = File.CreateText(path))
 {
      stream.Write(text);
 }

Be sure to look at the MSDN page for File.CreateText and StreamWriter.Write.

If you weren't targeting the .NET Compact Framework, as your tags suggest, you could do even simpler:

 File.WriteAllText(path, string);
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
2
System.IO.File.WriteAllText("myfile.txt", textBox.Text);

If you're stuck on some brain-dead version of the BCL, then you can write that function yourself:

static void WriteAllText(string path, string txt) {
    var bytes = Encoding.UTF8.GetBytes(txt);
    using (var f = File.OpenWrite(path)) {
        f.Write(bytes, 0, bytes.Length);
    }
}
Frank Krueger
  • 69,552
  • 46
  • 163
  • 208
1

Try this:

using System.Text;
using System.IO;
static void Main(string[] args)
{
  // replace string with your file path and name file.
  using (StreamWriter sw = new StreamWriter("line.txt"))
  {
    sw.WriteLine(MyTextBox.Text);
  }
}

Of course, add exception handling etc.

Traveling Tech Guy
  • 27,194
  • 23
  • 111
  • 159
0

For a richTextBox, you can add a "Save" button for this purpose. Also add a saveFileDialog control from Toolbox, then add following code in button's click event.

private void button1_Click(object sender, EventArgs e)
{
    DialogResult Result = saveFileDialog1.ShowDialog();//Show the dialog to save the file.
    //Test result and determine whether the user selected a file name from the saveFileDialog.
   if ((Result == DialogResult.OK) && (saveFileDialog1.FileName.Length > 0))
   {
       //Save the contents of the richTextBox into the file.
       richTextBox1.SaveFile(saveFileDialog1.FileName);
   } 
}
ePandit
  • 2,905
  • 2
  • 24
  • 15