radbyx
radbyx

Reputation: 9670

Can't read from newly created .txt. It's being used by another process

When I create my log.txt with File.Create(Path.Combine(PATH, NAME)); and then try to read from it I get an exception: {System.IO.IOException: The process cannot access the file 'c:\temp\log.txt' because it is being used by another process..

If the log.txt file exits and not created in the method I can read and write to the log wihtout any problems.

Is the log.txt created async and the problem is that the program is trying to read it before it's created?

public static void WriteToLog(string text)
{
    try
    {
        if (!Directory.Exists(PATH))
        {
            Directory.CreateDirectory(PATH);
        }

        if( !File.Exists(Path.Combine(PATH, NAME)) )
        {
            File.Create(Path.Combine(PATH, NAME));
        }

        var logLines = File.ReadAllLines(Path.Combine(PATH, NAME)).ToList<string>();
        logLines.Insert(0, "-------------------------------------------------End New Log");
        logLines.Insert(0, text);
        logLines.Insert(0, "-------------------------------------------------Start New Log");
        File.WriteAllLines(Path.Combine(PATH, NAME), logLines);
    }
    catch (Exception ex)
    {
    }
}

Upvotes: 0

Views: 793

Answers (2)

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239764

File.Create has a return value of type FileStream. That FileStream should be Closed (or Disposed) if you do not intend to use it for anything.

For a log file, however, I'd usually create the FileStream directly by constructing a FileStream object, using one of the constructors that accepts a FileShare parameter. That way, you can keep the stream open, but indicate that other programs should be able to open it for reading:

var fs = new FileStream(Path.Combine(PATH, NAME),
   FileMode.OpenOrCreate,
   FileAccess.Write,
   FileShare.Read); //Now other people can access the log file whilst I'm still writing to it

Upvotes: 3

user287107
user287107

Reputation: 9417

File.Create creates a filestream, which is open after the creation. so the file is used by its own process.

just change it to

        using(var f = File.Create(Path.Combine(PATH, NAME))) { } ;

Upvotes: 6

Related Questions