File.WriteAllText and Concurrent Accesses

前端 未结 3 927
小鲜肉
小鲜肉 2021-01-08 00:20

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 ot

3条回答
  •  -上瘾入骨i
    2021-01-08 01:04

    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);
    }
    

提交回复
热议问题