File.WriteAllText and Concurrent Accesses

人盡茶涼 提交于 2019-12-30 08:08:13

问题


Suppose I'm writing a very long string to a file using File.WriteAllText, and another thread or process is trying to read the same file. Would it throw any exception? In other words, what is the FileShare parameter that the File.WriteAllText method uses? It's not written in the documentation!


回答1:


This is the source code from .net Framework 4.0. clearly StreamWriter is used that Uses FileShare.Read Internally.

    [SecuritySafeCritical]
public static void WriteAllText(string path, string contents)
{
    if (path == null)
    {
        throw new ArgumentNullException("path");
    }
    if (path.Length == 0)
    {
        throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
    }
    InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM);
}


private static void InternalWriteAllText(string path, string contents, Encoding encoding)
{
    using (StreamWriter writer = new StreamWriter(path, false, encoding))
    {
        writer.Write(contents);
    }
}

This is the code that creates the underlying stream for StreamWriter.

private static Stream CreateFile(string path, bool append)
{
    return new FileStream(path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read, 0x1000, FileOptions.SequentialScan);
}



回答2:


MSDN doesn't document which sharing mode is used.

You could look at the source code (either published or via a disassembler), or look at the option at runtime (eg. using Process Monitor and then translating the WIn32 API flags into FileShare value).

But as it isn't documented a patch or new version could change it.

Alternatively if it matters open the file yourself using one of the FileStream overloads that takes a FileShare parameter, open a StreamWriter over this and then write the text.

Would it throw any exception?

Yes. If the file is open already with an incompatible sharing mode the open will fail.




回答3:


Would it throw any exception?

Yes. You should ensure that while one process is writing to a file others are not reading to it by using a lock. Even if you set the FileShare parameter to Read for example which would allow subsequent openings of the file for reading and not throw an exception immediately it is not a good idea as those readers would probably get corrupt results.



来源:https://stackoverflow.com/questions/6805757/file-writealltext-and-concurrent-accesses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!