2011-02-09 114 views
1

我使用OpenFileDialog來搜索特定文件。當用戶選擇文件時,我想將該路徑存儲在變量中。但是,這些在OpenFileDialog中似乎不是這個選項?C#FilePath幫助

有誰知道如何做到這一點?

謝謝。

編輯:這是Winforms,我不想保存路徑包括文件名,只是文件的位置。

+2

這是SL嗎? WPF?的WinForms? –

回答

1

這將基於對的FileName屬性來檢索您的路徑OpenFileDialog

String path = System.IO.Path.GetDirectoryName(OpenFileDialog.FileName); 
0

對話框關閉後,OpenFileDialog對象上應該有一個文件路徑(或類似的)屬性,它將存儲用戶輸入的任何文件路徑。

5

如果您使用WinForms,請使用OpenFileDialog實例的FileName屬性。

+0

僅僅作爲供參考,該屬性在SL中不存在;不知道OP在使用什麼...... –

+0

,最後是String path = System.IO.Path.GetDirectoryName(FileName); – rsapru

4

上的WinForms:

String fileName; 
OpenFileDialog ofd = new OpenFileDialog(); 
DialogResult dr = ofd.ShowDialog(); 
if (dr == DialogResult.Ok) { 
    fileName = ofd.FileName; 
} 

//getting only the path: 
String path = fileName.Substring(0, fileName.LastIndexOf('\\')); 

//or easier (thanks to Aaron) 
String path = System.IO.Path.GetDirectoryName(fileName); 
+0

這包括我不想要的文件名。只是文件包含的路徑。我應該更清楚一點。 –

+0

@Darren Young:編輯 – oopbase

+1

無需子串; String path = System.IO.Path.GetDirectoryName(fileName); –

0

嘗試文件名。或FileNames,如果你允許選擇多個文件(Multiselect = true)

1

而不是從MSDN複製粘貼答案我只會鏈接到他們。

關於Forms OpenFileDialog的MSDN文檔。

MSDN documentaiton on WPF OpenFileDialog

請在發佈問題前嘗試尋找答案。

1

您將路徑存儲在其他地方!

我通常會做的是創建一個用戶範圍的配置變量。

enter image description here

下面是其使用的樣本:

var filename = Properties.Settings.Default.LastDocument; 
var sfd = new Microsoft.Win32.SaveFileDialog(); 
sfd.FileName = filename; 
/* configure SFD */ 
var result = sfd.ShowDialog() ?? false; 
if (!result) 
    return; 
/* save stuff here */ 
Properties.Settings.Default.LastDocument = filename; 
Properties.Settings.Default.Save(); 

要保存剛纔的目錄,使用System.IO.Path.GetDirectoryName()

+0

謝謝,您的最終建議指出了我的正確方向。我使用System.IO.Directory.GetParent(openFileDialog1.FileName).ToString();這完美地工作。謝謝。 –