【问题标题】:How to run bat file with required permissions in C#如何在 C# 中运行具有所需权限的 bat 文件
【发布时间】:2012-02-15 15:26:38
【问题描述】:

我有一个 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-file 被执行,我可以在输出中看到 'Done!' 消息,但是文件没有被复制。

它的唯一工作方式是

psi.UseShellExecute = true;

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

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

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

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

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

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

请帮忙!

已编辑

感谢您的回复! 我花了几个小时试图处理这个问题,并且总是发生这种情况,我已经发布了我的问题并找到了解决方案:)

为了避免收到“句柄无效”消息,您必须这样做

psi.RedirectStandardInput = true;

但是现在我可以看到 cmd.exe 窗口,如果设置了 UserName,那就不好了。

【问题讨论】:

  • 如果您捕获XCOPY 的输出,它会说什么?如果权限是问题,它应该包括Access denied(或您的语言的等价物)。
  • 它什么也没说,静默失败,标准错误流中没有错误。
  • XCOPY 前面暂时放置一个ECHO。输出是否显示您期望的命令行(源/目标目录等)?
  • 另外,当失败发生时,argsfileToRun 到底是什么?
  • 是的,确实如此。我找到了解决方案,但现在我遇到了另一个问题 - 即使 psi.WindowStyle = ProcessWindowStyle.Hidden; 我也可以看到 cmd.exe 窗口psi.CreateNoWindow = true;

标签: c# process permissions batch-file


【解决方案1】:

你不见了

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

试试这个简单的 sn-p 应该对你有用

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

【讨论】:

猜你喜欢
  • 2014-01-22
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 2013-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多