在此目录中执行批处理文件

Executing Batch File At This Directory

我的 C# 窗体项目中使用了这段代码。我还有 exp.bat 文件包含 shell 命令,如下所示。 但是无论我做什么,它都不会在工作目录中创建 .txt 文件。

@echo off
echo "hello" > test.txt
path = @"‪C:\Users\abc\Desktop\exp.bat";
startingPath = @"C:\Users\abc\Desktop\";
bool success = false;
try
{
    System.Diagnostics.ProcessStartInfo ProcStartInfo = new 
    System.Diagnostics.ProcessStartInfo("cmd");
    ProcStartInfo.RedirectStandardOutput = true;
    ProcStartInfo.UseShellExecute = false;
    ProcStartInfo.CreateNoWindow = false;
    ProcStartInfo.RedirectStandardError = true;
    System.Diagnostics.Process MyProcess = new System.Diagnostics.Process();
    ProcStartInfo.Arguments = "/c start /wait"+path;
    ProcStartInfo.WorkingDirectory = startingPath;
    MyProcess.StartInfo = ProcStartInfo;
    success = MyProcess.Start();
    MyProcess.WaitForExit();
}
catch (Exception ex) { string s = ex.StackTrace.ToString();}

最初由在评论中使用 Mofi 发表。

发布相同的答案,所以这个问题不计入未回答,问题作者还在评论中确认 Mofi 的答案是正确的并且有帮助。

背景我觉得够了,这里评论作为答案。

In C# code use the method Environment.GetEnvironmentVariable to get the string value of predefined Windows environment variable USERPROFILE to build the paths for exp.bat and starting directory dynamically already within C# application. Or even better get current user desktop folder directly, see How to get a path to the desktop for the current user in C#?Mofi Feb 22 at 12:25

您可以通过将以下命令添加到您的 bat 文件的开头来轻松实现这一点。

 %~d0
 cd %~dp0