[.net] saving files in C#

Started by
9 comments, last by turnpast 18 years, 6 months ago
I am using C# 2005 and have set my file dialogue up but how can i print a string of characters out through it to a file?
Advertisement
Did you try looking in the System.IO namespace? Particularly System.IO.StreamWriter?
Proby is i can't find much stuff at all on how to use it for file output and then how to send it to my stream.
Something like this:

string someString = ...; using( StreamWriter writer = new StreamWriter(openFileDialog.Filename)){   writer.WriteLine(someString);}
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]
           using(StreamWriter sw = new StreamWriter("test.txt"))		{			sw.WriteLine("Test");		}
Quote:Original post by Arild Fines
Something like this:

*** Source Snippet Removed ***


ya beat me :P
It compiles but now i get an exception saying that my file is being used by another program. Here is my code.

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)        {             string someString = "Hello";              System.IO.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)                 {                     using (System.IO.StreamWriter writer = new System.IO.StreamWriter(saveFileDialog1.FileName))                     {                         writer.WriteLine(someString);                     }                  myStream.Close();                 }              }           }
	string someString = "Hello"; 						SaveFileDialog saveFileDialog1 = new SaveFileDialog(); 			saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"  ;			saveFileDialog1.FilterIndex = 2 ;			saveFileDialog1.RestoreDirectory = true ; 			if(saveFileDialog1.ShowDialog() == DialogResult.OK)			{									using (System.IO.StreamWriter writer = new System.IO.StreamWriter(saveFileDialog1.FileName))					{						writer.WriteLine(someString);					}								}
Thanks dude for all the help it works perfectly :). Now i will just try and see if i can get the data from within a html form.
Do not forget to close the stream writer! ever! :[]

use the System.IO namespace.

public void writeToFile(string message)
{
// Open the file
StreamWriter writer = new StreamWriter("test.txt")

// write the line to the file ..
writer.WriteLine(message);

// Close the file
writer.Close();

}

then call the function from your button or what ever triggers the write with

writeToFile("print this to the open file");

done .. hope that helps




This topic is closed to new replies.

Advertisement