2017-07-25 142 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

相關問題