Write to File after creating it ??? Known issue or my code?

T

Tat

Hello,
I have an error handling routine in Win app. If there is an error, the app
throws an exception and writes it to the text file all info about the error
so the app can send it to tech. If file doesn't exist to begin with, it
creates it. What happens is that after it creates file, it can't write to it
and blows up with the following: "The process cannot access the file "..."
because it is being used by another process"

Here is the outline of what I do:
FileInfo objFile = new FileInfo(appPath + @"\errors\errorlog.txt");
if(!objFile.Exists)
{
objFile.Create();
}
objFile = null;

objFile = new FileInfo(appPath + @"\errors\errorlog.txt");
StreamWriter sw = objFile.AppendText();
sw.WriteLine("error");
sw.Close();
sw = null;
objFile = null;

I used TextWriter, I didn't use FileInfo object for writing, I tried this
and that.
Please let me know what goes wrong and why app still keeps a hold of a file
that was created and how to work around it if it's a known issue. Needless
to say, if file is already created, it writes ok.
Thanks a bunch,
Tat
 
C

Chris Dunaway

Please let me know what goes wrong and why app still keeps a hold of a file

The create method, opens a stream for you. Just use code similar to this:

StreamWriter sw;
FileInfo objFile = new FileInfo(appPath + @"\errors\errorlog.txt");
if(!objFile.Exists)
{
sw = objFile.Create();
}
else
{
sw = objFile.AppendText();
}

sw.WriteLine("error");
sw.Close();
sw = null;
objFile = null;

--
Chris

dunawayc[AT]sbcglobal_lunchmeat_[DOT]net

To send me an E-mail, remove the "[", "]", underscores ,lunchmeat, and
replace certain words in my E-Mail address.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top