views:

293

answers:

3

Hello,

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

+3  A: 

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);
Martinho Fernandes
Thanks for your example and the reading indications, principally because of the indications! Continue like this! ;)
Nathan Campos
+2  A: 
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
+1 can't get any easier than this!
James
This is not supported in the CF.
Martinho Fernandes
+1  A: 

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
Duh! `using` *is* exception handling!
Martinho Fernandes
I meant some `try-catch` phrases to let the user know that a. the file cannot be created b. he has no permissions c. the text box is empty etc.
Traveling Tech Guy