2013-07-29 87 views
2

我有一些奇怪的問題(對我來說)。StreamReader路徑自動更改

有一個應用程序是一個Windows窗體應用程序「firstapp.exe」。 還有另外一個應用程序是windows窗體應用程序「launcher.exe」。 並且有一個名爲「server.exe」的控制檯應用程序。

firstapp和launcher都在同一目錄中。在該目錄中還有一個「Config」文件夾,其中包含一些其他文件。

,我用它來讀取config文件夾一個文件中firstapp代碼:

StreamReader reader = new StreamReader("Config\\launcher.txt"); 
string readed_config = reader.ReadToEnd(); 
reader.Close(); 

如果我運行啓動器(使用的Process.Start)的firstapp應用一切順利的罰款。 當我用控制檯應用程序運行它,它不在firstapp所在的同一目錄中時,我從代碼的該部分(上面發佈)中得到「目錄未找到異常」。

我該如何解決問題? 控制檯應用程序爲什麼要將自己的路徑添加到應該獨立運行的另一個應用程序?

+0

我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

+0

您可以使用'Environment.CurrentDirectory'來查看您所在的目錄,並對其進行更改。 –

+0

將'StreamReader'聲明和用法包裝在'using'語句中,並放棄'reader.Close();'。 –

回答

5

聽起來像你需要在調用Process.Start之前設置你的進程的WorkingDirectory屬性。

string launcherPath = @"C:\SomePathToLauncher\Launcher.exe"; 
myProcess.StartInfo.FileName = launcherPath; 
myProcess.StartInfo.WorkingDirectory = Path.GetDirectoryName(launcherPath); 
myProcess.Start(); 
+0

ProcessStartInfo startinfo = new ProcessStartInfo(); startinfo.FileName =「firstapp.exe」; startinfo.WorkingDirectory =「pathToAfolderWithFirstApp」; startinfo.Arguments =「arguments」 Process.Start(startinfo); – Doctorslo

0

答案在問題中。你在說「當我用控制檯應用程序運行它時,它不在同一個目錄中」。如果它不在同一個目錄下,如果它不存在,它將如何找到一個「Config」目錄。請確保該目錄存在

1

這是因爲您的路徑是相對的,當控制檯應用程序啓動winform時,當前工作目錄不同。此外,您應該將流式閱讀器封裝在using聲明中。就目前而言,除非您在代碼的其他地方明確地調用Dispose(),否則您將繼續使用應該釋放的資源。

要解決您的問題,請在使用Process.StartInfo.WorkingDirectory開始此過程時更改WorkingDirectory或更改代碼中的路徑,使其不相對。或者另一種選擇是將路徑傳遞給應用程序或從資源文件讀取它,以便在執行時爲其提供適當的路徑。在你的代碼

2
StreamReader reader = new StreamReader("Config\\launcher.txt"); 

決不使用硬編碼相對文件路徑。它關鍵取決於Environment.CurrentDirectory和方式太難以預料。當你發現外部代碼可以殺死你。內部代碼以及使用OpenFileDialog,您的代碼將崩潰。您可以隨時與Assembly.GetEntryAssembly()的位置和Path類的完整路徑:

var exedir = Path.GetDirectory(Assembly.GetEntryAssembly().Location); 
var path = Path.Combine(exedir, @"Config\launcher.txt"); 
using (var reader = new StreamReader(path)) { 
    //... 
} 

現在,它始終工作。