Click here to Skip to main content
15,891,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear all

I have to create error logs in my program.

i am able to write first line but afterwards it throws error " cannot write a to closed textwriter"

here is my code

System.IO.StreamWriter elog = new System.IO.StreamWriter(@"~\Logs\insert_into_table" + DateTime.Now.ToString("ddMMyyyy") + "." + DateTime.Now.ToString("hhmmss") + ".log", true);

using (elog)
{

elog.WriteLine("/************************************Logs Started*******************************************************/");
} ////this line writes well


try
{

using (elog)
{
elog.WriteLine("Connection to database open"); /// throwing exception here
elog.WriteLine("");
}

/




}

catch (Exception ee)
{
using (elog)
{
elog.WriteLine("exception occured. " + ee.Message); /// throwing exception here too

elog.WriteLine("");
}
Console.Write(ee);
}


}
}
}
Posted
Comments
George Swan 12-Feb-15 1:54am    
The 'using' statement calls the Dispose method on your streamWriter so it is closed after your first 'using' statement

1 solution

Just remove using() block, it automatically release the object at end.
 
Share this answer
 
Comments
Shilpa_g2 12-Feb-15 7:24am    
Thanks for reply... But after removing using() nothing is getting written in log file. not even first line

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900