Yogibear Yogibear - 1 month ago 11
C# Question

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 wheter they have administrator privileges. But remember, the the file is not running, so i need to basicly check if the software has 'run as administrator' checkbox set 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) stop the newly created process' main thread. Then a process is easier to check for elevated rights than a simple file, because runtime is the actual 'real' way the file behaves.

Answer

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";
}