如何在C#中以所需权限运行bat文件

4
我有一个.bat文件,它可以将文件从一个位置复制到另一个位置。
SET SRC=%1
SET DEST=%2

xcopy /Y/I %SRC%\*.txt %DEST%\temp
echo Done!

我正在尝试通过C#程序运行这个文件

var psi = new ProcessStartInfo(fileToRun);
psi.Arguments = args;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;

Process cmdProc = Process.Start(psi); 

StreamReader output = cmdProc.StandardOutput;
StreamReader errors = cmdProc.StandardError;
cmdProc.WaitForExit();

执行Bat文件时,我可以在输出中看到“完成!”消息,但是文件没有被复制。唯一的解决方法是:
psi.UseShellExecute = true;

psi.RedirectStandardOutput = false;
psi.RedirectStandardError = false;

但在这种情况下,我必须禁用输出/错误重定向并且需要它们。因此,这对我不起作用。

我尝试设置管理员的用户名/密码

psi.UserName = username;
psi.Password = password; 

登录成功,但在StandardError流中收到了'The handle is invalid'消息。

我猜想我正在尝试运行的进程没有复制文件的权限,我不知道如何授予它这些权限。

请帮忙!

编辑过的内容

谢谢回答! 我已经花费了几个小时来解决这个问题,正如常常发生的那样,我发布了我的问题并找到了解决方案 :)

为了避免获取'The handle is invalid'消息,你必须

psi.RedirectStandardInput = true;

但是现在,如果设置了用户名,我可以看到cmd.exe窗口,这是不好的。


如果你捕获了XCOPY的输出,它会说什么? 如果权限是问题,它应该包括“访问被拒绝”(或您语言的等效词)。 - Christian.K
它什么也没说,默默地失败了,在标准错误流中没有任何错误。 - Igor
在“XCOPY”前暂时加上“ECHO”。输出是否显示您期望的命令行(源/目标目录等)? - Christian.K
此外,当出现故障时,“args”和“fileToRun”中究竟包含什么? - Christian.K
理解:您想使用特定用户帐户启动批处理文件,当批处理文件运行时,它不应该要求/等待用户名和其他通过C#提供的信息,而应直接使用。正确吗? - Baljeetsingh Sucharia
显示剩余2条评论
1个回答

1
你缺失了。
psi.Domain = "domain";
psi.Verb ="runas";
//if you are using local user account then you need supply your machine name for domain

尝试使用这个简单的代码片段,应该可以为您工作。
void Main()
{
    string batchFilePathName =@"drive:\folder\filename.bat";
    ProcessStartInfo psi = new ProcessStartInfo(batchFilePathName);

    psi.Arguments = "arg1 arg2";//if any
    psi.WindowStyle = ProcessWindowStyle.Hidden;
    psi.UseShellExecute = false;
    psi.Verb ="runas";
    psi.UserName = "UserName"; //domain\username
    psi.Domain = "domain"; //domain\username
    //if you are using local user account then you need supply your machine name for domain

    psi.WindowStyle = ProcessWindowStyle.Hidden;
    psi.UseShellExecute = false;
    psi.Verb ="runas";

    Process ps = new Process(psi);
    Process.Start(ps);  
}

如果您遇到任何Windows UAC问题,这可能会很方便:https://dev59.com/m3E85IYBdhLWcg3wXCIv - Baljeetsingh Sucharia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接