我正在编写以下代码.
static void Main(string[] args)
{
FileInfo fiobj = new FileInfo(@"e:\mohan.txt");
Console.Write("Name of file:"+ fiobj.Name);
using(StreamWriter sw = fiobj.AppendText())
{
sw.WriteLine("mohan!");
}
}
// code not working
static void Main(string[] args)
{
FileInfo fiobj = new FileInfo(@"e:\mohan.txt");
Console.Write("Name of file:"+ fiobj.Name);
StreamWriter sw = fiobj.AppendText();
sw.WriteLine("mohan!");
}
Run Code Online (Sandbox Code Playgroud)
当我使用"using(){}"块时,我能够写入文件,但是当我在不使用(){}块的情况下编写相同的代码时,我无法做到.为什么这样?据我所知,using(){}块指定对象的生命周期范围.使用(){}阻止在这里执行某些操作以使其能够将数据写入文件.
一旦范围落在块之外,这using是正确确保对象Disposed正确的简写using.
您的代码相当于:
StreamWriter sw = fiobj.AppendText();
try
{
sw.WriteLine("mohan!");
}
finally
{
if (sw != null)
{
((IDisposable)sw).Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
此代码正确关闭并处理StreamWriter.没有它,它将保持锁定状态.