Jump to content
  • Advertisement
Sign in to follow this  
GameMasterXL

[.net] saving files in C#

This topic is 4695 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement
Something like this:


string someString = ...;
using( StreamWriter writer = new StreamWriter(openFileDialog.Filename))
{
writer.WriteLine(someString);
}

Share this post


Link to post
Share on other sites
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!