简体   繁体   中英

what happens if multiple users call C# File.WriteAllText at the same time to the same location?

tldr; If multiple users/instances of an application call File.WriteAllText() to the same filepath at the same time, what will happen? will the call throw an exception, will the call throw an exception and corrupt the file, will the call 'succeed' but still potentially corrupt the file, will the OS schedule one to happen after the other or will some other thing happen?

We have an application that saves config settings each time they use our application's main feature. The config is saved to the app's install folder, to the same path each time. We now have a client that wants to have multiple users running the application from the same install path. If a conflict results in the config not saving that's not an issue, but if the conflict results in corruption it would be inconvenient. I just need to know the likelihood of the call corrupting the file and not throwing an error?

Any help or links to sources would be greatly appreciated, I couldn't find anything when I was looking.

Thanks in advance

Edit: With FileStream, and with FileShare.Read, if another user tries to read the file in the middle of a write, will he get the earlier version of the file? or will he get an incomplete file? this is not a large file being written, but would it be necessary to set it to FileShare.None and add retries to the file.read as well or not?

It turns out it produces an exception (I ran four instances of the application and closed them all at the same time, all but one threw an exception), File.WriteAllText() appears to lock the file. Just to be safe though, FileStream seems to give the ability to do this explicitly

using (FileStream writer = new FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.Read)) {
    writer.Write(jsonString));
    writer.Flush();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM