Question

I know the answer must be out there somewhere, I applied suggestions both from many other questions and from MSDN itself but I'm probably overlooking something here.

This is my method, I use it to dump output to file. lock object declaration attached for clarity.

private static Object fileLock = new Object();
private static void WriteToFile(string msg, bool WriteLine)
{
    lock (fileLock)
    {
        msg = DateTime.Now.ToShortTimeString() + " - " + msg;

        FileInfo F = new FileInfo("dump.txt");
        using (StreamWriter writer = F.Exists ? F.AppendText() : F.CreateText()) //<--THIS LINE THROWS
        {
            if (WriteLine)
                writer.WriteLine(msg);
            else
                writer.Write(msg);
        }
    }
}

Question is: Why does the using line above throws an IOException complaining another process is using the file the 2nd time I call the method ?

I'm calling it like this around my code:

Console.WriteLine(something)
#if(DEBUG)
    Extensions.WriteToFile(something,true);
#endif

Again, I'm sure this is a trivial issue and someone else asked something like this getting the right answer, but I'm unable to dig it up.

UPDATE

Refactoring out the FileInfo object and switching to File.XXX methods made the code work fine. I still wonder what the issue was, anyway the issue looks like solved.

Était-ce utile?

La solution

@Guffa: declaration has to be private static object fileLock = new object();

@alex: Your code works just fine on my machine although it's a bit too complicated for the task imo.

static void Write(string text, string file)
    {
        using (StreamWriter sw = File.AppendText(file))// Creates or opens and appends
        {
            sw.WriteLine(text);
        }
    }

Maybe some antivirus or indexer locks your dump file.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top