Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

c# - Why does impersonating a process return "The directory name is invalid"?

I have a process that needs to run under administrative privileges. I need the average joe to run the process, but I don't want to give everyone access... so I've created a simple class that will run this ONE task as an administrator, using impersonation.

The code is VERY striaght-forward, but I can't understand why this is crashing. HELP??!!

I'm running this via a batch file, and I've even copied the file that needs to execute to the local hard drive, thinking this might be a permission issue for running an app over the network.

    public static Process ImpersonateProcess(string exe, string args, string Username, string Password)
    {
        ProcessStartInfo psi = new ProcessStartInfo(exe);
        psi.Arguments = args;
        psi.UseShellExecute = false;
        psi.UserName = Username;

        psi.Password = new SecureString();

        foreach (char c in Password.ToCharArray())
        {
            psi.Password.AppendChar(c);
        }

        Process proc = null;

        Console.WriteLine("starting...");
        proc = Process.Start(psi);
        Console.WriteLine("started");

        return proc;
    }

In the code above, I never get to "started". It throws an error in the Process.Start(psi) and with an error message of "the directory name is invalid."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It could be because you're not setting the WorkingDirectory property. According to the docs:

Important Note:

The WorkingDirectory property must be set if UserName and Password are provided. If the property is not set, the default working directory is %SYSTEMROOT%system32.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...