Exception when using FileInfo.Create

I am trying to implement a .log file in my application but keep running into an unhandled exception that I don't understand. The log file creation and updating is handled by a class named LogFile show below:

public class LogFile
{
string filePath = @"xyz.log";

public LogFile()

/// <summary>
/// Initializes the log file. If the file does not exist, it is created. If it exists, new log info is concatenated onto the end of the file
/// </summary>
public void InitLogFile()
{
FileInfo fi=new FileInfo(filePath);
{
if (fi.Exists)
{
if (fi.Length>2000000)
{
fi.Delete();
fi.Create();
}
}
else fi.Create();
return ;
}
}

/// <summary>
/// Log the current state
/// </summary>
public bool LogState()
{
FileInfo fi = new FileInfo(filePath);
StreamWriter sw = fi.AppendText();
sw.WriteLine(CreateLogString());
sw.Flush();
sw.Close();
return true;
}

private string CreateLogString()
{
string logString;
MyBoard mBoard = new MyBoard();
mBoard.PollmBoard();

logString = Convert.ToString(DateTime.Now)
+", s="+Convert.ToString(mBoard.cb.State)
+", bv="+Convert.ToString(mBoard.cb.Batt_V)
+", bc="+Convert.ToString(mBoard.cb.Batt_C)
+", pv="+Convert.ToString(mBoard.cb.PriOut_V)
+", pc="+Convert.ToString(mBoard.cb.PriOut_C)
+", sv="+Convert.ToString(mBoard.cb.SecOut_V)
+", sc="+Convert.ToString(mBoard.cb.SecOut_C)
+", tp="+Convert.ToString(mBoard.cb.Temp)
+", fc="+Convert.ToString(mBoard.cb.FaultCode)
+", ll="+Convert.ToString(mBoard.cb.LEDS_lsb)
+", lh="+Convert.ToString(mBoard.cb.LEDS_msb);
return logString;

}
}
}

***************

However, if the log file does not exist (first time running the app) I get the following exception:

************** Exception Text **************
System.IO.IOException: The process cannot access the file "C:\Documents and Settings\Mike\My Documents\Visual Studio Projects\P2120CS\bin\Debug\psumoni.log" because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String str)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean useAsync, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at System.IO.StreamWriter.CreateFile(String path, Boolean append)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
at System.IO.StreamWriter..ctor(String path, Boolean append)
at System.IO.FileInfo.AppendText()
at P2120CS.LogFile.LogState() in c:\documents and settings\mike\my documents\visual studio projects\p2120cs\logstate.cs:line 48
at P2120CS.Form1.pollTimer_Tick(Object sender, EventArgs e) in c:\documents and settings\mike\my documents\visual studio projects\p2120cs\cnx-p2120.cs:line 1693
at System.Windows.Forms.Timer.OnTick(EventArgs e)
at System.Windows.Forms.Timer.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr idEvent, IntPtr dwTime)

*********************

Can anyone spot the problem Your help would be appreciated!



Answer this question

Exception when using FileInfo.Create

  • Andrea

    FileInfo.Create returns a FileStream. You're not doing anything with that FileStream, and it's not getting garbage collected before you try to open another writing stream to the same file. Admittedly the error message is incorrect in terms of the process...

    Just change the call to FileInfo.Create to call Dispose on the stream which is returned, and everything should be okay.

    Jon


  • John Sewell

    That's not quite what I was suggesting. Wherever you've got "fi.Create" you should have "fi.Create().Dispose()" to immediately dispose of the FileStream after creating it.

    Jon



  • Amit Bhagwat

    OK Jon, I think I've figured it out. At least I'm not getting the exception with this modified code:

    /// <summary>

    /// Initializes the log file. If the file does not exist, it is created. If it exists, new log info is concatenated onto the end of the file

    /// </summary>

    public void InitLogFile()

    {

    FileInfo fi = new FileInfo(filePath);

    StreamWriter sw = fi.AppendText();

    {

    if (fi.Exists)

    {

    if (fi.Length>2000000)

    {

    fi.Delete();

    fi.Create();

    }

    }

    else fi.Create();

    }

    sw.Close();

    return;

    }


  • Bruce Taimana

    Jon,

    Thanks for the attempt to help, but I am not quite sure how to impelent your suggested fix. Can you be a bit more specific Are you suggesting that, after fi.create() I add a line to call Dispose Can you show me the context of this line Sorry for the newbie questions, but,....I am ...;)


  • Fred Reimer

    Ahh...Thanks. Works!
  • Exception when using FileInfo.Create