尝试使用以下代码从 C# 解决方案运行外部可执行文件(带有依赖项(时,我得到了一个Win32Exception
File not found
。
public static string TestMethod()
{
try
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = Path.Combine("dist", @"test.exe");
p.Start();
}
catch (Exception ex)
{
expMessage = ex.Message;
}
return expMessage;
}
言论:
- 将绝对路径指定为
FileName
时不会发生异常。 - 在 MS Visual Studio 中,
dist
子文件夹文件属性设置为以下内容,并且dist
目录确实复制到输出文件夹中:Build action: Content
Always copy in output directory
- 我尝试使用如下
test.exe.config
文件,但没有成功:
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="dist"/>
</assemblyBinding>
</runtime>
</configuration>
编辑在这种情况下实际有效的指定相对路径中提出的唯一解决方案是最终由Viacheslav Smityukh作为评论提供的解决方案,结合AppDomain.CurrentDomain.SetupInformation.ApplicationBase
来重建绝对路径。然而,正如Pavel Pája Halbich在下面的回答中所述,运行时似乎存在一个潜在的问题。从 如何在 .NET 控制台应用程序中获取应用程序的路径?我使用以下代码根据 Mr.Mindor 的评论找到了另一种解决方案:
string uriPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
string localPath = new Uri(uriPath).LocalPath;
string testpath = Path.Combine(localPath, "dist", @"test.exe");
现在我想知道哪一个是考虑未来使用窗口安装程序部署解决方案的正确方法。
> 在您的情况下,dist
路径是当前工作目录,它不符合您的期望。
尝试将路径更改为:
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dist", @"test.exe");
您需要指定该可执行文件的完整路径。因此,您可以使用System.Reflection.Assembly.GetExecutingAssembly().Location
导致
Path.Combine(System.IO.Path.GetDirectoryName( iSystem.Reflection.Assembly.GetExecutingAssembly().Location), "dist", @"test.exe");
正如您在这个问题中所看到的,如何在 .NET 控制台应用程序中获取应用程序的路径?,使用AppDomain.CurrentDomain.BaseDirectory
可以工作,但不建议使用它 - 它可以在运行时更改。
编辑更正了获取目录而不是可执行文件的完整位置的答案。