C#:直接执行一个程序和被另一个进程调用的区别

C#:Difference between executing a program directly and call by another process

我编写了一个名为 "CopyFile" 的程序来重复将文件从本地复制到网络共享文件夹,如下所示:

List<string> log = new List<string>();
string originPath = "*LOCAL PATH*";
string targetPath = "*TARGET PATH*";

System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;

if (File.Exists(originPath))
{
  p.Start();
  StreamWriter sw = p.StandardInput;
  sw.WriteLine(@"NET USE *TARGET IP* *PASSWORD* /USER:*USERNAME*");
  sw.WriteLine(@"COPY "+'"'+originPath+'"'+ " "+'"'+targetPath+'"');
  sw.WriteLine("Y");
  sw.WriteLine("EXIT");
  sw.Close();                  
  p.WaitForExit();

  log.Add(p.StandardOutput.ReadToEnd());
}
else 
{                  
  log.Add("No file");   
}

我在我的电脑上试过这个程序,如果我双击执行这个程序,程序就执行成功了。但是如果我使用另一个 C# 程序或 windows 任务调度程序来调用并执行它。程序无法正常运行。我检查了日志文件以查看输出。双击执行日志显示:

D:\Downtime>NET USE *TARGET IP* *PASSWORD* /USER:*USERNAME*
The command complete successfully.
D:\Downtime>COPY *originpath* *targetpath*
1 file(s) copied.
D:\Downtime>EXIT

但如果我使用另一个 C# 程序或 windows 任务调度程序来执行它,日志显示

C:\Windows\system32>NET USE *TARGET IP* *PASSWORD* /USER:*USERNAME*

C:\Windows\system32>COPY *originpath* *targetpath*
0 file(s) copied.

C:\Windows\system32>EXIT

看起来如果我通过另一个程序或 windows 任务调度程序调用它 "cmd.exe" 将不会执行命令 "NET USE" 所以我无法连接到网络计算机并将文件复制到它。 有谁知道问题出在哪里?谢谢

不知道你的路径是绝对路径还是相对路径。如果您在代码中使用相对路径,则应考虑设置 ProcessStartInfo 实例的 WorkingDirectory 属性。

当你直接调用你的程序时。 WorkingDirectory 是包含可执行文件的目录。

当您从其他进程调用您的程序时,工作目录是其他进程的目录 - 而不是您的程序。

所以在这种情况下,您必须正确设置 WorkingDirectory 属性。

here 阅读更多内容。