2010-07-21 88 views
3

我有代碼以2種不同的形式檢索direcotry路徑。如果在一種形式中,我選擇一個路徑來打開一個文件並處理它,當返回到另一個表單時,我得到一個Direcotry Exception錯誤。我用不同的字符串來獲取路徑爲什麼路徑發生變化

在第二種形式我叫這個:

 string strFilePath2; 
     strFilePath2 = Directory.GetCurrentDirectory(); 
     strFilePath2 = Directory.GetParent(strFilePath2).ToString(); 
     strFilePath2 = Directory.GetParent(strFilePath2).ToString(); 
     strFilePath2 = strFilePath2 + "\\ACH"; 

在我的第一個形式我叫:

 strFilePath = Directory.GetCurrentDirectory(); 
     strFilePath = Directory.GetParent(strFilePath).ToString(); 
     strFilePath = Directory.GetParent(strFilePath).ToString(); 
     strFilePath = strFilePath + "\\ACH\\" + Node; 

在調試過程中,我得到的選擇第二種形式的路徑,但不是我期望的路徑。任何人都可以說明原因嗎?

+0

請在問題中加入例外。 – 2010-07-21 08:41:10

回答

8

您是否檢查當前目錄的值?

OpenFileDialog通常會改變當前目錄。您可以使用RestoreDirectory屬性來控制這種行爲:

OpenFileDialog ofd = new OpenFileDialog(); 

ofd.RestoreDirectory = true ; // this will not modify the current directory 

順便說一句,你是串聯您的代碼示例中的路徑。在.NET中,最好使用靜態的Path.Combine方法完成。此方法將檢查一個反斜槓(或其他系統的路徑分隔符),並自動存在插入一個如果它缺少:

strFilePath = Path.Combine(strFilePath, "ACH"); 
3

通常這取決於撥打電話FolderBrowserDialogOpenFileDialog或類似的東西。這些對話框(以及其他組件)會自動更改正在運行的應用程序的工作目錄。

我的建議是避免使用相對路徑,如果有任何種類的用戶交互。

+0

我使用Openfiledialog,你可以建議如何過來這個。 – Dotnet 2010-07-21 08:47:57

+0

請看Mark的好解釋:-) – 2010-07-21 09:02:10

3

OpenFileDialogSaveFileDialog改變當前的工作路徑,這是很煩人的。您可以手動重置該選項,也可以設置.RestoreDirectory = true;以在選擇文件後更改它。如果您使用的是FolderBrowserDialog,如果您仍然遇到此問題,則必須手動執行此操作。

相關問題