Sign in to follow this  
GameMasterXL

[.net] saving files in C#

Recommended Posts

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();
}
}
}


Share this post


Link to post
Share on other sites


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);
}

}


Share this post


Link to post
Share on other sites
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




Share this post


Link to post
Share on other sites
Quote:
Original post by k00k
Do not forget to close the stream writer! ever! :[]


The using statement should take care of that for you. It will ensure that the stream is disposed when the block is exited.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this