2

我想从streamwriter的内容中保存文件,但是在这段代码中

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

在行中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");

一切正常!问题出在哪里?谢谢 !

4

3 回答 3

6

您只需要添加大括号:

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

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

for 的范围规则与 forusing()相同if(),您已经正确使用了它。

于 2012-08-02T11:50:32.633 回答
3

试试这样:

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!
 }

当您不使用大括号时,它只会看到下面的第一行代码。

于 2012-08-02T11:51:23.327 回答
0

Using statement,当它定义一个对象将被释放的范围时。请参阅使用语句

于 2012-08-02T11:56:17.817 回答