Reputation: 97
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 !
Upvotes: 2
Views: 3992
Reputation: 10347
Using statement
, when it defines a scope at the end of which an object will be disposed. See using Statement.
Upvotes: 0
Reputation: 34013
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.
Upvotes: 3
Reputation: 273264
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.
Upvotes: 6