I want bild save file from contents in streamwriter, but in this code
SaveFileDialog savefile = new SaveFileDialog();
savefile.FileName = "unknown.txt";
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*|";
if (savefile.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(savefile.FileName, false, System.Text.Encoding.Unicode))
sw.WriteLine("Test line");
sw.WriteLine("Test line2");
sw.WriteLine("Test line3");
}
in lines sw.WriteLine("Test line2");
sw.WriteLine("Test line3"); , are errors, sw didn't exist !
But rarely i used code
using (StreamWriter sw = new StreamWriter("\unknow.txt", false,System.Text.Encoding.Unicode))
sw.WriteLine("Test line");
sw.WriteLine("Test line2");
sw.WriteLine("Test line3");
and everything work's fine ! Where is problem ? Thank's !
You just need to add braces:
using (StreamWriter sw = new StreamWriter(savefile.FileName,
false, System.Text.Encoding.Unicode))
{
sw.WriteLine("Test line");
sw.WriteLine("Test line2");
sw.WriteLine("Test line3");
}
The variable sw is local to the scope of the using() statement. Without the braces that was only the first WriteLine().
The scoping rules for using() are the same as for if(), you were already using that correctly.
Try it like this:
SaveFileDialog savefile = new SaveFileDialog();
savefile.FileName = "unknown.txt";
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*|";
if (savefile.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(savefile.FileName, false, System.Text.Encoding.Unicode))
{ // You are missing this one..
sw.WriteLine("Test line");
sw.WriteLine("Test line2");
sw.WriteLine("Test line3");
} //.. and this one!
}
When you don't use the braces it will only see the first following line of code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With