runtime icon indicating copy to clipboard operation
runtime copied to clipboard

FileInfo.Open() with FileMode.Append throws unexpected exception

Open ianhays opened this issue 11 years ago • 1 comments

The following code is an example of the situation:

string fileName = GetTestFilePath();
using (FileStream fs = new FileInfo(fileName).Open(FileMode.Create))
{
    fs.WriteByte(0);
}
using (FileStream fs = new FileInfo(fileName).Open(FileMode.Append)) // Throws ArgumentException: append access can be requested only in write-only mode
{ }

The issue is a result of the default FileAccess value used in the FileInfo.Open(FileMode) method:

public FileStream Open(FileMode mode)
{
    return Open(mode, FileAccess.ReadWrite, FileShare.None);
}

when it should be the same as what File.Open(FileMode) does like so:

public FileStream Open(FileMode mode)
{
    return Open(mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None);
}

ianhays avatar Jul 23 '15 17:07 ianhays

cc: @ericstj

stephentoub avatar Jul 23 '15 17:07 stephentoub