K
kengtung
Greetings all,
I just started programming with C# (.Net FW 1.1) last year and still
learning. Previously I am using VB 6.0.
Recently, in one application, I encountered a C# error "Cannot write
to a closed TextWriter.". I looked at the code and it looks ok to me.
Maybe I am missing some understanding here on the inner function of
TextWriter. Any information is much appreciated.
Another question is should I close both textWriter and streamWriter or
just the streamWriter? I just want to make sure there is no stream
objects left in the memory when GC runs.
Code snippets:
[STAThread]
static void Main(string[] args)
{
string filePath = Directory.GetCurrentDirectory() + "\\test.htm";
StreamWriter streamWriter = null;
if( File.Exists( filePath ) )
streamWriter = new StreamWriter( filePath );
else
streamWriter = File.CreateText( filePath );
XmlTextWriter textWriter = new XmlTextWriter( streamWriter );
try
{
textWriter.WriteStartElement("start");
textWriter.WriteElementString("data", "123");
textWriter.WriteEndElement();
}
finally
{
if (textWriter != null)
{
textWriter.Flush();
textWriter.Close();
textWriter = null;
}
if (streamWriter != null)
{
streamWriter.Flush();
streamWriter.Close();
streamWriter = null;
}
}
}
<EOC>
Many thanks in advance.
KT Lee.
I just started programming with C# (.Net FW 1.1) last year and still
learning. Previously I am using VB 6.0.
Recently, in one application, I encountered a C# error "Cannot write
to a closed TextWriter.". I looked at the code and it looks ok to me.
Maybe I am missing some understanding here on the inner function of
TextWriter. Any information is much appreciated.
Another question is should I close both textWriter and streamWriter or
just the streamWriter? I just want to make sure there is no stream
objects left in the memory when GC runs.
Code snippets:
[STAThread]
static void Main(string[] args)
{
string filePath = Directory.GetCurrentDirectory() + "\\test.htm";
StreamWriter streamWriter = null;
if( File.Exists( filePath ) )
streamWriter = new StreamWriter( filePath );
else
streamWriter = File.CreateText( filePath );
XmlTextWriter textWriter = new XmlTextWriter( streamWriter );
try
{
textWriter.WriteStartElement("start");
textWriter.WriteElementString("data", "123");
textWriter.WriteEndElement();
}
finally
{
if (textWriter != null)
{
textWriter.Flush();
textWriter.Close();
textWriter = null;
}
if (streamWriter != null)
{
streamWriter.Flush();
streamWriter.Close();
streamWriter = null;
}
}
}
<EOC>
Many thanks in advance.
KT Lee.