2

I am trying to create a log file using the code given below, but it is raising the following error: -

The Process Cannot access the file because it is being used by another process

Kindly help me out in this regard.

The code is as given below: -

string logFile = System.IO.Directory.GetCurrentDirectory() + "\\LogFile\\" + DateTime.Now.ToString("dd-MM-yyyy") + "TaskLogFile.txt";
StreamWriter LogWriter = null;

try
{
    if (!File.Exists(logFile))
    {      
        LogWriter = new StreamWriter(logFile);
        Console.WriteLine("Log File Created...");
    }
    else
    {
        LogWriter = File.AppendText(logFile);
        Console.WriteLine("Log File Appended...");
    }

    if (EX == null)
    {
        LogWriter.Write("\r\nLog Entry : ");
        LogWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
        LogWriter.WriteLine("\nTask Id = {0} , Task Name = {1}, Service Name = {2} ", TaskId, TaskName, ServiceName);
        LogWriter.WriteLine("-----------------------------------------------------------------------------------------------------");
    }

    else
    {
        LogWriter.WriteLine("\n Error : {0}, Error Location : {1},Task ID = {2}, Task Name : {3}, Service Name : {4} " + EX.ToString(), EX.StackTrace, TaskId, TaskName, ServiceName);
    }

}

catch (Exception ex)
{
    LogWriter = File.AppendText(logFile);
    LogWriter.WriteLine("\n Error : {0}" + ex.ToString());
}


finally
{
    if (LogWriter != null)
    {
        LogWriter.Close();     
    }
    LogWriter = null;
}
Konamiman
  • 49,681
  • 17
  • 108
  • 138
Harsh
  • 173
  • 1
  • 3
  • 11
  • 6
    An exception during file operations does not close the file handle - your `catch` clause is trying to open a file that's already open (for writing, with sharing disabled). Not to mention that the scope of that `catch` is so broad it might catch an error while opening the file initially, or while doing the `WriteLine` etc. Oh, and don't forget that someone else might have the file open as well :) – Luaan Jun 15 '15 at 06:33
  • 1
    Once you've ensured you've fixed your code itself, you can use [SysInternals Process Explorer](https://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) to work out if something else is locking it. – Reddog Jun 15 '15 at 06:42
  • @Luaan I tried to ignore the exception, but the error still persists. – Harsh Jun 15 '15 at 06:50
  • "another process" is less than helpful in this exception message since frequently (as here), the "other process" is in fact your own. As @Luaan's comment says, you attempt to *re-open* the file in your `catch` clause, so that's one location where you trip over yourself. – Damien_The_Unbeliever Jun 15 '15 at 06:52
  • 1
    if you use that function on multiple threads you might want to wait for the file to be accessible, something like http://stackoverflow.com/questions/12268067/filesystemwatcher-is-file-ready-to-use if you do not need to implement the logging yourself you could use a logging framework like log4net – fuchs777 Jun 15 '15 at 06:54
  • 2
    You should probably use a logging library like log4net instead of trying to write your own. File management and multithreaded access are just two of the issues you need to address. Moreover, .NET already provides logging support which *does* address these problems – Panagiotis Kanavos Jun 15 '15 at 07:16
  • Moreover, an exception in the *logging* code shouldn't be trying to write to the log file that caused the exception - most likely it will fail as well. Log such errors to a different file or TraceListener – Panagiotis Kanavos Jun 15 '15 at 07:17

2 Answers2

1

update your catch(){} block with this and try;

catch (Exception ex)
    {

        if (LogWriter != null)
        {
            LogWriter.Close();     
        }
        LogWriter = File.AppendText(logFile);
        LogWriter.WriteLine("\n Error : {0}" + ex.ToString());
    }

Hope it helps..!

H. Mahida
  • 2,356
  • 1
  • 12
  • 23
0

I'd suggest to use File.AppendAllText() method because it is simplest solution, a good one for this purpose. This method does exactly what your logger should do - it opens a file, appends it with a line of text (or number of text lines) and closes it right away.

Why to use filestream?

Fabjan
  • 13,506
  • 4
  • 25
  • 52