[.net] saving files in C#
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?
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);}
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
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
Popular Topics
Advertisement