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.AppendText();
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.
The
usingis shorthand for correctly ensuring that your object isDisposedcorrectly once the scope falls outside of theusingblock.Your code is equivalent to:
This code correctly closed and disposes of the StreamWriter. Without it, it would remain locked.
Source