Home > Software design >  c# File.WriteAllBytes raises "Access denied" exception, while "FileStream.Write"
c# File.WriteAllBytes raises "Access denied" exception, while "FileStream.Write"

Time:03-12

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.

CodePudding user response:

What happens when you run the program with elevated permissions? Does the issue still happen? If you're still getting an access denied with elevated privelages, you probably have something else (if not your own program) have a hold on that file. See if you can open a FileStream and write that way, it'll likely give you more info. I'll write up a better answer if and when I hear the results of doing that. I would comment but I don't have enough rep yet.

CodePudding user response:

To write to a Binary File you need BinaryWriter.

 public static void WriteDefaultValues()
    {
        using (var stream = File.Open(fileName, FileMode.Create))
        {
            using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
            {
                writer.Write(1.250F);
                writer.Write(@"c:\Temp");
                writer.Write(10);
                writer.Write(true);
            }
        }
    }
  • Related