Using keyword in FileInfo
I am writing following code.
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.AppendTex开发者_运维问答t();
sw.WriteLine("mohan!");
}
When I use the "using(){}" block I am able to write into file but when I wrote the same code without using(){} block I am not able to do So. Why is So? As far as I know using(){} block specifies the scope of the object for it's life time. Does using(){} block doing something fancy here to make it enable to write the data to file.
Without the using
statement, you aren't closing the StreamWriter
.
Therefore, the StreamWriter remains open and the file remains locked.
The using
is shorthand for correctly ensuring that your object is Disposed
correctly once the scope falls outside of the using
block.
Your code is equivalent to:
StreamWriter sw = fiobj.AppendText();
try
{
sw.WriteLine("mohan!");
}
finally
{
if (sw != null)
{
((IDisposable)sw).Dispose();
}
}
This code correctly closed and disposes of the StreamWriter. Without it, it would remain locked.
Source
精彩评论