سؤال

I have a bit of a strange situation, where a privileged script (i.e. it has been UAC-ed) is unable to write 'normally' to a file. That is, trying to write to the file path using either a StreamWriter or via a FileStream with a mode of FileMode.Create or similar throws an UnauthorizedAccessException, however using FileMode.Truncate works perfectly!

The file in question is the Group Policy scripts.ini file, located at C:\Windows\Sysnative\GroupPolicy\Machine\Scripts\scripts.ini. (Note: sysnative is required for me as Windows thinks it's a great idea to rewrite system32 to syswow64 just because my OS is 64-bit...).

Now this is mostly a theoretical question, since I do have a workaround (i.e. to use FileMode.Truncate), but I was wondering if anyone knew how a privileged script can end up being unable to write to a file? It seems especially strange since FileMode.Create is meant to be equivalent to FileMode.Truncate for existing files.

Sample code - insert the above filename (if you dare - please do take a backup first, especially if you have shutdown scripts registered...), compile, and use Run As Administrator:

using System;
using System.IO;
using System.Security.Principal;

class Program
{
    static void Main(string[] args)
    {
        WindowsIdentity identity = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(identity);

        // Outputs true.
        Console.WriteLine(principal.IsInRole(WindowsBuiltInRole.Administrator));

        // Throws an UnauthorizedAccessException.
        // using (var w = new StreamWriter(@"filename_here"))

        // Also throws UnauthorizedAccessException.
        // using (var fs = new FileStream(@"filename_here", FileMode.Create, FileAccess.ReadWrite))

        // Works!
        using (var fs = new FileStream(@"filename_here", FileMode.Truncate, FileAccess.ReadWrite))
        {    
            var w = new StreamWriter(fs);
            w.WriteLine("Test");

            w.Close();
        }

        Console.WriteLine("Press any key to close...");
        Console.ReadLine();
    }
}
هل كانت مفيدة؟

المحلول

Just checked the msdn notes for FileMode FileMode Enumeration

it mentions for FileMode.Create
If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top