Search code examples
c#securityfile-permissionsadministrator

How could I check if a (non process) file is administrator


Simple question, but couldn't find anything useful. I need to iterate through files and check whether they have administrator privileges. But remember, the file is not running, so I need to basically check if the software has a 'run as administrator' checkbox set to true or false. Probably this has something to do with attributes I guess. So, how could I achieve that? (I have no idea...)

Edit: I found another way to do this, I did not test it yet. To start the file as a process, immediately (without Thread.Sleep or any operations) suspend the newly created process' main thread. Then a process is easier to check for elevated rights than a simple file because the runtime is the actual 'real' way the file behaves.


Solution

  • You can use the below method. You can define variable acording to your requirement.

    string sShortcutPath="";
            string sAppName="";
            string sDesktopPath="";
            string vbScript = GENERICVBFILE.Replace("@@SHORTCUTPATH@@", sShortcutPath);
            vbScript = vbScript.Replace("@@SHORTCUTNAME@@", sAppName);
            vbScript = vbScript.Replace("@@DESKTOPFOLDER@@", sDesktopPath);
            string vbFile = "Script.vbs";
            if (File.Exists(vbFile))
                File.Delete(vbFile);
            File.WriteAllText(vbFile, vbScript);
            Process cProc = new Process();
            cProc.StartInfo.FileName = "cscript.exe";
            cProc.StartInfo.Arguments = vbFile;
            cProc.StartInfo.UseShellExecute = false;
            cProc.StartInfo.CreateNoWindow = true;
            cProc.Start();
    
    
        public const string GENERICVBFILE =
            "Option Explicit\n" +
            "Dim ShellApp, FSO, Desktop\n" +
            "Set ShellApp = CreateObject(\"Shell.Application\")\n" +
            "Set FSO = CreateObject(\"Scripting.FileSystemObject\")\n" +
    
            "Set Desktop =  ShellApp.NameSpace(\"@@DESKTOPFOLDER@@\")\n" +
            "Dim LnkFile\n" +
            "LnkFile = \"@@SHORTCUTPATH@@\"\n" +
    
            "If(FSO.FileExists(LnkFile)) Then\n" +
            "Dim verb\n" +
            "Dim desktopImtes, item\n" +
            "Set desktopImtes = Desktop.Items()\n" +
    
            "For Each item in desktopImtes\n" +
            "If (item.Name = \"@@SHORTCUTNAME@@\") Then\n" +
            "For Each verb in item.Verbs\n" +
            "If (verb.Name = \"Run as &administrator\") _\n" +
            "Then\n" +
            "verb.DoIt\n" +
            "End If\n" +
            "Next\n" +
            "End If\n" +
            "Next\n" +
            "End If";
    }