1 year ago

#282724

test-img

Disti

c# File.WriteAllBytes raises "Access denied" exception, while "FileStream.Write" succeeds

I have the following code:

var cnt = new byte[] { 0xaa, 0xbb };
var fileName = @"C:\ProgramData\path\to\myfile.bin";

try
{
    File.WriteAllBytes(fileName, cnt);
    Console.WriteLine(("WriteAllBytes OK"));
}
catch (Exception ex)
{
    Console.WriteLine("WriteAllBytes Exception: " + ex.Message);
}

try
{
    using (var f = new FileStream(fileName, FileMode.Open))
    {
        f.Write(cnt, 0, 2);
        f.Close();
        Console.WriteLine("FileStream.Write OK");
    }
}
catch (Exception ex)
{
    Console.WriteLine("FileStream.Write Exception: " + ex.Message);
}

this code gives the following output:

WriteAllBytes Exception: Access denied to path 'C:\ProgramData\path\to\myfile.bin'.
FileStream.Write OK

I added Everyone/Full control to file permissions and assigned file ownership to MYPC\MyUser.

I used Process Monitor to see what's going on, this is the output:

CreateFile C:\ProgramData\Path\to\myfile.bin ACCESS DENIED Desired Access: Generic Write, Read Attributes, Disposition: OverwriteIf, Options: Synchronous IO Non-Alert, Non-Directory File, Open No Recall, Attributes: n/a, ShareMode: Read, AllocationSize: 0 MYPC\MyUser 00000000:0002d238

CreateFile C:\ProgramData\Path\to\myfile.bin SUCCESS Desired Access: Generic Read/Write, Disposition: Open, Options: Synchronous IO Non-Alert, Non-Directory File, Open No Recall, Attributes: n/a, ShareMode: Read, AllocationSize: n/a, OpenResult: Opened MYPC\MyUser 00000000:0002d238 WriteFile C:\ProgramData\Path\to\myfile.bin SUCCESS Offset: 0, Length: 2, Priority: Normal MYPC\MyUser 00000000:0002d238 CloseFile C:\ProgramData\Path\to\myfile.bin SUCCESS MYPC\MyUser 00000000:0002d238

I don't understand why in this situation WriteToFile fails.

c#

windows

ntfs

0 Answers

Your Answer

Accepted video resources