Abluescarab
Abluescarab

Reputation: 547

Show a UAC prompt only when installed in a protected folder

I have an application that can be installed anywhere. I don't want it to prompt the user when the program is in an unprotected folder. Is it possible to only show a UAC prompt when the application is in Program Files (or a similar protected folder)?

I'm using this code at the moment to check if it has write access (from this question):

public static bool HasWriteAccess(string folder) {
    try {
        System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(folder);
        return true;
    }
    catch(UnauthorizedAccessException) {
        return false;
    }
}

I know that the code cannot be run in Program.cs or frmMain_Load because that is after the application has started, and so won't work.

Upvotes: 0

Views: 123

Answers (1)

Lev
Lev

Reputation: 434

I just wrote a small test to see if the idea works. This works:

    static void Main(string[] args)
    {
        string _name = Assembly.GetExecutingAssembly().Location + Guid.NewGuid().ToString();
        try
        {
            File.CreateText(_name).Close();
            File.Delete(_name);
        }
        catch (UnauthorizedAccessException)
        {
            Restart();
            return;
        }

        Console.WriteLine("execution with write access");
        Console.ReadKey();
    }

    private static void Restart()
    {
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = Assembly.GetExecutingAssembly().Location;
        startInfo.Verb = "runas";
        Process p = Process.Start(startInfo);
    }

Upvotes: 1

Related Questions