在没有管理员权限的情况下从 C# 使用 Git-bash

时间:2021-06-08 14:43:52

标签: python c# batch-file git-bash

我试图启动 python 虚拟环境并使用以下代码从 C# 文件运行 python 文件。

public static void ExecuteGitBashCommand(string fileName, string command, string workingDir)
    {

        ProcessStartInfo processStartInfo = new ProcessStartInfo(fileName, "-c \" " + command + " \"")
        {
            WorkingDirectory = workingDir,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            RedirectStandardInput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };

        var process = Process.Start(processStartInfo);
        process.WaitForExit();

        string output = process.StandardOutput.ReadToEnd();
        string error = process.StandardError.ReadToEnd();
        var exitCode = process.ExitCode;

        process.Close();
    }

运行时我收到一条错误消息“System.ComponentModel.Win32Exception: 'Access is denied.'” 环顾四周,我看到的建议是以管理员身份运行,但这不是一个选项。有没有办法做到这一点?运行代码的用户有权限运行git-bash。

编辑 1:

我开始考虑使用 .BAT 文件,但要做到这一点,我需要使用 bat 激活虚拟环境的第二个 bat 文件,这导致它无法运行 bat 文件的第二部分。无论如何让它在同一个命令提示符下执行这两个命令将解决问题。

1 个答案:

答案 0 :(得分:1)

我使用 bat 文件解决了这个问题,该文件不需要管理员权限即可从 C# 代码运行。并使用 call 命令从批处理文件中执行另一个批处理文件。我还使用了另一个 SO 帖子在批处理文件中使用了相对路径文件。

relative path in BAT script