views:

366

answers:

3

Okay, I'm probably missing something really simple here, but I've been at this for over an hour now and getting nowhere. :( I have a C# project using Microsoft's Visual C# 2008 Express Edition. The Save dialog box appears as desired, but it never makes the file. Practially speaking, once the file is specified, I'd like the application to maintain it with current data as a log file. For now, I'd just be happy, if I could get the ####### thing to make an empty file. Here's what I've been able to come up with so far:

      private void saveLogAsToolStripMenuItem_Click(object sender, EventArgs e)
      {
         if (DialogResult.OK == saveFileDialog1.ShowDialog())
         {
            // If the file name is not an empty string open it for saving.
            if (saveFileDialog1.FileName != "")
            {
/* This does not work.
               // Saves the Image via a FileStream created by the OpenFile method.
               System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();
               fs.Write((byte)"Success!\r\n", 0, 10);
               fs.Close();
*/
            }
            else
            {
               textBox1.Text += "An invalid filename was specified.\r\n";
            }

         }
      }

Any suggestions would be much appreciated. Thanks.

+3  A: 

This will work:

using (System.IO.TextWriter tw = new System.IO.StreamWriter(saveFileDialog1.FileName))
{
    tw.WriteLine("Success");
}
Gabriel McAdams
A: 
FileInfo fi = new FileInfo(saveFileDialog1.Filename); 
StreamWriter stm = fi.OpenWrite;
// or
FileStream stm = fi.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); 
John Knoeller
+3  A: 

Gabriel's answer is correct, except that he's using saveFileDialog1.FileName directly, rather than the OpenFile() method on SaveFileDialog. If you want your application to work in partial-trust environments then you need to use OpenFile() and access the stread directly.

See this MSDN article for more info.

Here's the equivalent code:

using (var stream = dlg.OpenFile())
using (var writer = new System.IO.StreamWriter(stream))
{
    writer.WriteLine("Success");
}
Matt Hamilton
Thanks Matt; that works great!
Jim Fell