2

I need to write a file in a async way, every half a second. And I can only use C# on .Net Framework 2.0 .

I tried using File.Create and BeginWrite. But it keeps the file locked, and I need to be able to access it (read). I tried fiddling with the security settings but I'm not really sure what I'm doing there.

Any help is appreciated!

Edit:

var bytes = Encoding.ASCII.GetBytes(stringBuilder.ToString());
var filePath = Path.Combine(OUTPUT_FOLDER, FILE_NAME);
var fileSteam = File.Create(filePath, bytes.Length, FileOptions.Asynchronous);
m_IAsyncResult = fileSteam.BeginWrite(bytes, 0, int.MaxValue, WriteCallback, new State(fileSteam));

private void WriteCallback(IAsyncResult ar) {
    var state = (State)ar.AsyncState;
    var stream = state.Stream;
    stream.EndWrite(ar);

    m_IAsyncResult = null;
}

2 Answers2

2

You need to make sure that the file is opened non-exclusively. Check this post How can I read a text file without locking it?

Community
  • 1
  • 1
Steven
  • 43
  • 4
0

If you can use File.WriteAllText or File.AppendAllText both will handle the open and close for you allowing you to read again later without issue.

JStevens
  • 2,090
  • 1
  • 22
  • 26