我必须在c#代码中启动一个可执行文件(installPrint.exe)。为此,我使用了System.Diagnostics.Process类。exe文件安装打印机驱动程序并将几个文件复制到不同的目录中。我可以从命令行执行exe,一切工作正常。但是,如果我使用c#应用程序中的Process类执行该文件,则不会安装打印机驱动程序。
我在Windows XP SP2 x86机器上以admin用户启动c#应用程序。为什么我的可执行文件不能在我的c#应用程序的上下文中工作?我有什么可能让它工作?
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Arguments = "-i "My Printer" -dir . -port myPort -spooler";
startInfo.CreateNoWindow = true;
startInfo.FileName = @"C:Printerinstall.exe";
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
//startInfo.Verb = "runas";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.WorkingDirectory = @"C:Printer";
session.Log("Working Directory: " + startInfo.WorkingDirectory);
session.Log("Executing " + startInfo.FileName);
try
{
Process process = new Process();
//process.EnableRaisingEvents = false;
process.StartInfo = startInfo;
process.Start();
session.Log("installer.exe started");
StreamReader outReader = process.StandardOutput;
StreamReader errReader = process.StandardError;
process.WaitForExit();
//session.Log(outReader.ReadToEnd());
//session.Log(errReader.ReadToEnd());
session.Log("RETURN CODE: " + process.ExitCode);
}
catch (Exception ex)
{
session.Log("An error occurred during printer installation.");
session.Log(ex.ToString());
}
我猜你是在Windows Vista或Windows 7上运行程序。然后,您必须请求提升新创建的进程以完全访问权限运行。看看这些问题的细节:如果路径受到保护,请求Windows Vista UAC提升?Windows 7和Vista UAC -在c#中以编程方式请求提升
好的,我现在知道了,你用的是Win XP。那么这可能是因为您启动进程时的一些设置。尝试以ShellExecute方式启动进程,这样它将最接近于用户正常启动。下面是一个示例:
var p = new System.Diagnostics.Process();
p.StartInfo = new System.Diagnostics.ProcessStartInfo { FileName = "yourfile.exe", UseShellExecute = true };
p.Start();
我在我的项目的许多部分使用这个类:
public class ExecutableLauncher
{
private string _pathExe;
public ExecutableLauncher(string pathExe)
{
_pathExe = pathExe;
}
public bool StartProcessAndWaitEnd(string argoment, bool useShellExecute)
{
try
{
Process currentProcess = new Process();
currentProcess.EnableRaisingEvents = false;
currentProcess.StartInfo.UseShellExecute = useShellExecute;
currentProcess.StartInfo.FileName = _pathExe;
// Es.: currentProcess.StartInfo.Arguments="http://www.microsoft.com";
currentProcess.StartInfo.Arguments = argoment;
currentProcess.Start();
currentProcess.WaitForExit();
currentProcess.Close();
return true;
}
catch (Exception currentException)
{
throw currentException;
}
}
}
我希望已经回答了你的问题。
m .