2017-07-25 25 views
0

我得到一个Win32ExceptionFile not found试图运行从下面的代码C#解决方案的外部可执行文件(具有相关性)时。运行在C#解决方案外部可执行使用相对路径

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> 

编辑Specifying a relative path其实际工作在这种情况下提出的唯一的解决办法是最终提供由维亚切Smityukh结合​​3210重建的绝对路径注释的一个。但是,PavelPájaHalbich在下面的回答中指出,运行时似乎存在潜在的问题。从How can I get the application's path in a .NET console application?我发现使用下面的代码基于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"); 

现在,我不知道哪一个是考虑与窗口安装的解决方案的未来部署的正确方法。

+0

[指定相对路径]的可能重复(https://stackoverflow.com/questions/5077475/specifying-a-relative-path) –

回答

1

,以你的情况dist的路径是当前工作目录,这是不符合您的期望对齐。

试着改变你的路径:

Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "dist", @"test.exe");

+0

您有两个缺陷 - 首先,您使用的只是字符串,而不是'BaseDirectory 'Path.Combine'中第一个参数的属性。此外,'BaseDirectory'可以在运行时设置,因此它不是一个好的做法(但它可以工作) –

+0

@Connor感谢:它结合了'AppDomain.CurrentDomain.BaseDirectory'时按预期工作。但是,因为它似乎不被推荐,它是否令人满意?特别是如果我想稍后使用Windows Installer分发解决方案?我很惊讶没有规范的方式来执行这样的标准任务。 –

+0

@AntoineGautier这是我一直这样做的方式。 Pavel的正确之处在于,在创建AppDomain时可以将其设置为不同的内容,但除非您使用AppDomains(创建或销毁),否则应该安全地使用它。 – Connor

0

你需要指定路径,可执行文件。所以,你可以使用System.Reflection.Assembly.GetExecutingAssembly().Location导致

Path.Combine(System.IO.Path.GetDirectoryName(iSystem.Reflection.Assembly.GetExecutingAssembly().Location), "dist", @"test.exe"); 

,你可以在本身这个问题How can I get the application's path in a .NET console application?,使用AppDomain.CurrentDomain.BaseDirectory可以工作,但它不是recommened - 它可以在运行时改变。

编辑修正答案越来越目录,而不是充满位置的可执行。

+0

我已经尝试过将'System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly()。Location')结合起来,在我的情况下它返回'C:\ Users \ Ang \ AppData \ Local \ assembly \ dl3 \ 967GPNG9 .0M7 \ DMDMB1C2.7XQ \ b710451e \ c711a674_7f05d301'并且不能解决问题。即使在运行期间手动将'dist'子文件夹添加到此位置也无济于事。 –

+0

我认为这种方法所面临的挑战在于它没有考虑到卷影副本,就像从网络共享中运行程序一样。您在技术上寻找的程序集和文件夹驻留在服务器上,并且不在正在执行的本地副本中。 – Connor

相关问题