我有一个在我的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();}
答案 0 :(得分:0)
最初使用Mofi发表在评论中。
按原样发布相同的答案,这样就不会在未回答的问题中算出该问题,问题作者还在评论中确认Mofi的回答是正确的,并有所帮助。
我认为背景足够,这是评论。
在C#代码中,使用方法Environment.GetEnvironmentVariable获取预定义Windows环境变量USERPROFILE的字符串值,以构建exp.bat的路径并已在C#应用程序中动态启动目录。甚至最好直接获取当前用户的桌面文件夹,请参阅How to get a path to the desktop for the current user in C#? – Mofi 2月22日12:25
答案 1 :(得分:0)
通过将以下命令添加到bat文件的开头,可以轻松实现此目的。
%~d0
cd %~dp0