如何在 C# 中以所需权限运行 bat 文件
我有一个 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();
执行该文件来运行此文件,我可以在输出中看到 'Done!' 消息,但文件不会被复制。
它的唯一工作方式是
psi.UseShellExecute = true;
psi.RedirectStandardOutput = false;
psi.RedirectStandardError = false;
但在这种情况下我必须禁用输出/错误重定向,我需要它们。 所以这对我不起作用。
我尝试设置管理员的用户名/密码
psi.UserName = username;
psi.Password = password;
登录成功,但在 StandardError 流中收到“句柄无效”消息。
我想我尝试运行的进程没有复制文件的权限并且 我不知道如何授予他这些权限。
请帮忙!
已编辑
感谢您的回复! 我花了几个小时尝试处理这个问题,并且总是发生这样的情况,我已经发布了我的问题并找到了解决方案:)
为了避免收到“句柄无效”消息,您必须
psi.RedirectStandardInput = true;
但现在我可以看到cmd.exe窗口,如果设置了UserName,这是不好的。
I have a bat file that copies files from one location to another.
SET SRC=%1
SET DEST=%2
xcopy /Y/I %SRC%\*.txt %DEST%\temp
echo Done!
I'm trying to run this file via C# program
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-file is executed, I can see the 'Done!' message in the output, but files are not copied.
The only way it works is
psi.UseShellExecute = true;
psi.RedirectStandardOutput = false;
psi.RedirectStandardError = false;
But in this case I have to disable output/error redirection and I need them.
So this doesn't work for me.
I have tried to set administrator's username/password
psi.UserName = username;
psi.Password = password;
Logon succeed, but I get the 'The handle is invalid' message in the StandardError Stream.
I guess the process I'm trying to run doesn't have permissions to copy files and
I don't know how to grant him these permissions.
Please, help!
EDITED
Thank you for replies!
I have spend several hours trying to handle this issue and as it always happens I have posted my question and found the solution :)
In order to avoid getting 'The handle is invalid' message you have to
psi.RedirectStandardInput = true;
But now I can see cmd.exe window, if UserName is set, which is bad.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你错过了
尝试这个简单的片段应该适合你
you are missing
try this simple snippet should work for you