C#:直接执行程序与另一个进程调用之间的区别

时间:2016-07-14 01:44:48

标签: c# cmd process scheduled-tasks

我编写了一个名为“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”,因此我无法连接到网络计算机并将文件复制到它。 有谁知道这是什么问题?感谢。

1 个答案:

答案 0 :(得分:0)

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

直接拨打程序时。 WorkingDirectory是包含可执行文件的目录。

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

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

here了解详情。