0

I am trying to create a file with a FileInfo object and I am getting strange behavior.

Here is the gist of what I am doing -

    public void CreateLog()
    {
        FileInfo LogFile = new FileInfo("");

        if (!LogFile.Directory.Exists) { LogFile.Directory.Create(); }
        if (!LogFile.Exists) { LogFile.Create(); }

        if (LogFile.Length == 0)
        {
            using (StreamWriter Writer = LogFile.AppendText())
            {
                Writer.WriteLine("Quotes for " + Instrument.InstrumentID);
                Writer.WriteLine("Time,Bid Size,Bid Price,Ask Price,Ask Size");
            }
        }
    }

However, when it checks to see the length of the logfile, it says that the file does not exist (I checked - it does exist).

When I substitute LogFile.Length with the following:

    File.ReadAllLines(LogFile.FullName).Length;

Then I get an exception that says that it cannot access the file because something else is already accessing it.

BUT, if I do a Thread.Sleep(500) before I do ReadAllLines, then it seems to work fine.

What am I missing?

William
  • 3,335
  • 9
  • 42
  • 74

1 Answers1

0

LogFile.Create() if you user this function ,you may lock the file, so you can use using ,like this
using(LogFile.Create()){}

after that you can use the file again

gyluo
  • 1