WPF選擇文件、文件夾和另存為對話框


 

一 WPF

1.1 選擇文件對話框

OpenFileDialog類存在於PresentationFramework.dll程序集。
 1 public string SelectFileWpf()
 2         {
 3             var openFileDialog = new Microsoft.Win32.OpenFileDialog()
 4             {
 5                 Filter = "Text documents (.txt)|*.txt|All files (*.*)|*.*"
 6             };
 7             var result = openFileDialog.ShowDialog();
 8             if (result == true)
 9             {
10                 return openFileDialog.FileName;
11             }
12             else
13             {
14                 return null;
15             }
16         }

 1.2選擇文件夾

WPF提供了選擇文件對話框,但並沒有提供選擇文件夾的對話框。

1.3另存為對話框

SaveFileDialog類位於PresentationFramework.dll 的Microsoft.Win32命名空間

public static string ChooseSaveFile(string title,string initFolder)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Title = title;
            dlg.FileName = "User.txt"; // Default file name
            dlg.DefaultExt = ".txt"; // Default file extension
            dlg.Filter = "Text documents|*.txt"; // Filter files by extension
            dlg.InitialDirectory = initFolder;

            // Process save file dialog box results
            if (dlg.ShowDialog() == true)
            {
                return dlg.FileName;
            }
            else
            {
                return null;
            }
        }

 

二 WinForm

下面需要添加System.Windows.Forms.dll

2.1選擇文件

 

1  public string SelectFile() //彈出一個選擇文件的對話框
2         {
3             OpenFileDialog file = new OpenFileDialog(); 4  file.ShowDialog(); 5 return file.SafeFileName; 6 }

 

 

2.2選擇文件夾

using System.Windows.Forms;

FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog(); if (folderBrowserDialog.ShowDialog() == DialogResult.OK) { string outDir = folderBrowserDialog.SelectedPath; }

 

 

 

參考:

https://docs.microsoft.com/zh-cn/dotnet/api/system.windows.forms.openfiledialog?view=netframework-4.7.2

C# 文件過濾器filter

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM