[英]C# FilePath Help
我使用OpenFileDialog搜索特定文件。 當用戶選擇文件時,我想將該路徑存儲在變量中。 但是,這些似乎不是OpenFileDialog中的選項嗎?
有人知道怎么做這個嗎?
謝謝。
編輯:這是Winforms,我不想保存包含文件名的路徑,而只保存文件所在的位置。
如果使用的是WinForms,請使用OpenFileDialog
實例的FileName
屬性。
在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);
您將路徑存儲在其他地方!
我通常要做的是創建一個用戶范圍的配置變量。
以下是其用法示例:
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()
這將基於OpenFileDialog
的FileName
屬性檢索路徑。
String path = System.IO.Path.GetDirectoryName(OpenFileDialog.FileName);
對話框關閉后,OpenFileDialog對象上應有一個文件路徑(或類似內容)屬性,它將存儲用戶輸入的任何文件路徑。
嘗試使用FileName。 如果允許選擇多個文件,則為FileNames(Multiselect = true)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.