我的应用程序中的 运行 批处理文件有问题

Problem with running batch files from within my application

我一直在尝试创建一个简单的应用程序来备份我的 Windows 服务器数据库以及整个服务器备份。 为此,我想使用我的应用程序正在执行的批处理文件。 我尝试了几种方法,但出于某种原因,它总是失败,所以如果你能帮助我,我会很高兴。

批处理文件 BACKUPSERVER:

wbadmin start backup -backupTarget:D: -include:C: -allCritical -quiet

我必须 运行 以管理员身份安装 bat,否则会因缺少权限而失败。

C#代码:

        static Task<int> RunProcessAsync(string fileName)
        {
        ............
        Process p = new Process();

        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.Verb = "runas";
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = "/C \"D:\SQLBACKUP\BACKUPSERVER.bat\"";
        p.Start();

        string output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();

        }

调试说 'wbadmin wasnt found'。 'runas'激活与否没有任何区别。

                 ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = fileName;

        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError = true;
        startInfo.UseShellExecute = true;
        startInfo.CreateNoWindow = false;
       // startInfo.Verb = "runas";

        var process = new Process

        {

            StartInfo = { FileName = fileName },
            EnableRaisingEvents = true

        };
        process.StartInfo = startInfo;

        process.Exited += (sender, args) =>
        {
            tcs.SetResult(process.ExitCode);
            process.Dispose();
        };

        process.Start();

同样无效。

有什么想法吗?

编辑: 我可以 运行 命令,如关机,但 wbadmin 根本不起作用...

我是这样解决问题的:

  1. 如果您打算在 64 位系统上使用您的应用程序,请确保编译为 64 位,否则它将重定向到不同的子文件夹并且找不到 'wbadmin.exe'.

  2. 运行 wbadmin 与 ProcessStart 或 运行 批处理但没有直接 cmd 输入,因此将其与 filename = 批处理文件或 wbadmin 与 startInfo.Arguments 一起使用:

        ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.FileName = fileName;
    
    startInfo.RedirectStandardOutput = true;
    startInfo.RedirectStandardError = true;
    startInfo.UseShellExecute = true;
    startInfo.CreateNoWindow = false;
    

    // startInfo.Verb = "runas";

    var process = new Process
    
    {
    
        StartInfo = { FileName = fileName },
        EnableRaisingEvents = true
    
    };
    process.StartInfo = startInfo;
    
    process.Exited += (sender, args) =>
    {
        tcs.SetResult(process.ExitCode);
        process.Dispose();
    };
    
    process.Start();
    
  3. 确保你请求管理员权限