0

I am getting the "this is being used by another process" error with my Faillog class. The code for it is below. It happens on the line "using (StreamWriter sw = new StreamWriter(path + file, true))" in the Log method. I have no idea what I am doing wrong, because nothing else appears to be accessing the file. It seems impossible, too, because an instance of the class is created when the program is first run, then when used two seconds later it is somehow being used by another process. I would like some help on figuring out what is causing this error.

class Faillog
{
    #region Private Variables
    //The location of the Faillog file.
    private string path;

    //The name of the file used for marking failures.
    private string file;
    #endregion

    #region Constructor
    public Faillog(string p = @"C:\RH Faillog\", string f = "default")
    {
        path = p;
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }

        if (f == "default")
        {
            file = "Faillog_" + DateTime.Now.ToShortDateString().Replace("/", "-") + ".txt";
        }
        else
        {
            file = f;
        }

        if (!File.Exists(path + file))
        {
            File.Create(path + file);
        }
    }
    #endregion

    #region Getters
    public string GetPath()
    {
        return path;
    }

    public string GetFile()
    {
        return file;
    }
    #endregion

    #region Public Methods
    //Logs a fail record into the file.
    public void Log(string name)
    {
        using (StreamWriter sw = new StreamWriter(path + file, true))
        {
            sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt") + ": " + name + " failed.");
        }
    }
    #endregion
11clock
  • 61
  • 2
  • 6

2 Answers2

1

You need to close the file;

   file.Flush();
    file.Close();
ChrisBint
  • 12,773
  • 6
  • 40
  • 62
0

File.Create returns a FileStream which you are ignoring, so the underlying file handle is not getting released (and closed) in a timely manner.

You shouldn't need to explicitly create the file anyways. The StreamWriter should create the file for you if it doesn't exist.

D Stanley
  • 149,601
  • 11
  • 178
  • 240