SaveFileDialog在c#中使用streamwriter出现问题

use*_*839 1 c# using

我想从streamwriter中的内容中使用bild保存文件,但是在此代码中

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");
                }
Run Code Online (Sandbox Code Playgroud)

在行sw.WriteLine("Test line2"); sw.WriteLine("Test line3");,是错误,sw不存在!

但我很少使用代码

using (StreamWriter sw = new StreamWriter("\unknow.txt", false,System.Text.Encoding.Unicode)) sw.WriteLine("Test line"); sw.WriteLine("Test line2"); sw.WriteLine("Test line3");

一切正常!哪里有问题?谢谢 !

Hen*_*man 5

你只需要添加大括号:

using (StreamWriter sw = new StreamWriter(savefile.FileName, 
          false, System.Text.Encoding.Unicode))
{
     sw.WriteLine("Test line");
     sw.WriteLine("Test line2");
     sw.WriteLine("Test line3");
}
Run Code Online (Sandbox Code Playgroud)

该变量swusing()语句范围的本地变量.没有大括号只是第一个WriteLine().

范围规则using()是相同的if(),您已经正确使用它.