天天看點

C#選擇檔案對話框

添加System.Windows.Forms引用

選擇檔案

private void PhotoPathElect_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog();//打開檔案對話框 
            fileDialog.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory;//初始化路徑
            fileDialog.Filter = "圖檔(*.*)|*.*";//或"圖檔(*.jpg;*.bmp)|*.jpg;*.bmp";//過濾選項設定,文本檔案,所有檔案。
            fileDialog.FilterIndex = 0;//目前使用第二個過濾字元串
            fileDialog.RestoreDirectory = true;//對話框關閉時恢複原目錄
            fileDialog.Title = "選擇圖檔";
            if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                PhotoPath.Text = fileDialog.FileName;
            }
        }
           

選擇檔案或檔案夾(隻能選擇沒有目錄的檔案夾)

public void SelectFolder()
        {
            System.Windows.Forms.OpenFileDialog folderBrowser = new System.Windows.Forms.OpenFileDialog();
            // Set validate names and check file exists to false otherwise windows will
            // not let you select "Folder Selection."
            folderBrowser.ValidateNames = false;
            folderBrowser.CheckFileExists = false;
            folderBrowser.CheckPathExists = true;
            // Always default to Folder Selection.
            folderBrowser.FileName = "Folder Selection.";
            if (folderBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string folderPath = Path.GetDirectoryName(folderBrowser.FileName);
                // ...
            }
        }
           

選擇目錄

System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
dialog.Description = "please select the folder path";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    string foldPath = dialog.SelectedPath;
    FolderPath = foldPath;
}
           

繼續閱讀