1
string fileText;
using (var reader = File.OpenText(pathToSave)) {
    fileText = await reader.ReadToEndAsync();
    reader.Close();
}

using (var stream = File.Open(pathToSave, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) {
    Byte[] text = new UTF8Encoding(true).GetBytes("test1" + Environment.NewLine);
    stream.Write(text, 0, text.Length);

    text = new UTF8Encoding(true).GetBytes("test2" + Environment.NewLine);
    stream.Write(text, 0, text.Length);

    stream.Close();
}

I don't operate with files anywhere else.

I always close file descriptors after reading / writing, but I still get an error, that the file is used by another process.

What do I do wrong?

The error appears on FileMode.Append.

John Doe
  • 21
  • 1
  • 1
    You need to post the complete error and stack trace. – Jonathan Alfaro Apr 13 '20 at 19:59
  • 1
    Why are you writing to the stream directly? You could just use `File.ReadAllText` and then either use a method like `File.AppendAllText` or keep using `File.Open` but use a `StreamWriter` so you don't have to work with bytes. Read [this](https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-write-text-to-a-file). – Joelius Apr 13 '20 at 20:02

2 Answers2

1

I tried your code and it seems fileText = await reader.ReadToEndAsync(); locks the file, so you need to complete this task before using this file again.

You can use ReadToEnd instead of ReadToEndAsync to run synchronously:

string fileText;
using (var reader = File.OpenText(pathToSave)) {
    fileText = reader.ReadToEnd();
    reader.Close();
}
Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
0

@John Doe Replying to your comment, sadly I don't have enough reputation to do it in the comments. Yes of course you can! Check this out https://stackoverflow.com/a/9396092/13294196 (and also the question in that thread to understand it if you don't) EDIT: and make sure to see Joelius's advice about using streamreader and streamwriter, it's a much better solution than operating on bytes.

Nekuskus
  • 143
  • 1
  • 11