OpenFileDialog 用於瀏覽並打開文件,在Windows Forms中使用,表現為標准的Windows對話框。
實例:
1.新建Windows Form Application
2.添加OpenFileDialog
打開Toolbox,找到並雙擊OpenFileDialog:
可以在窗口下方看到添加到OpenFileDialog.
3.添加按鈕和事件
OpenFileDialog對話框需要通過事件激活,添加一個Button到Form中,雙擊Button以添加事件,事件代碼如下:
using System; using System.Windows.Forms; namespace OpenFileDialog { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // show the dialog and get result DialogResult result = openFileDialog1.ShowDialog(); if (result == DialogResult.OK) { } Console.WriteLine(result); } } }
4.讀取文件
可以通過OpenFileDialog讀取文件,修改按鈕的點擊事件,具體代碼如下:
using System; using System.IO; using System.Windows.Forms; namespace OpenFileDialog { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { int size = -1; // show the dialog and get result DialogResult result = openFileDialog1.ShowDialog(); if (result == DialogResult.OK) { string file = openFileDialog1.FileName; try { string text = File.ReadAllText(file); size = text.Length; } catch (Exception) { throw; } } Console.WriteLine(result); Console.WriteLine(size); // 文件大小 } } }
編譯運行,點擊button1,會顯示OpenFileDialog,然后驗證DialogResult,通過File.ReadAllText讀寫文件,然后獲得文件大小。
5. 屬性
屬性 | 說明 |
AddExtension | 擴展名是否添加到文件名,默認為真,如果想自動修改文件擴展名,可將其設置為false。 |
AutoUpgradeEnabled | 用於獲得Vista風格的打開文件對話框,默認為true,推薦使用。 |
DefaultExt | 默認文件擴展名,如果文件擴展名沒有指定,則自動添加該擴展 |
DereferenceLinks | 從對話框返回路徑前是否解引用快捷鍵 |
FileName | 在對話框最開始顯式的文件名 |
InitialDirectory | 對話框的初始目錄 |
Multiselect | 是否一次可選擇多個文件,可通過SHIFT或CTRL鍵進行多項選擇 |
6.Filter
Filters能幫助有效的篩選文件,OpenFileDialog支持文件名過濾,可用*代表任意字符。
Filter:
用於指定過濾器,如:“C# files|*.cs”,此時只顯式以”.cs”結尾的文件
FilterIndex:
用於指定默認Filter,其Index為1.其后的filter的Index依次遞增
ValidateNames:
Windows文件系統不允許文件名包含特定字符如”*”,該選項一般為True。
7.ReadOnly
OpenFileDialog部分屬性可允許指定文件是否為只讀。可以顯式read-only checkbox。大多時候用不着.
ReadOnlyChecked:
用於設置”read only”復選框的值,僅當”ShowReadOnly”設置為True才可見。
ShowReadOnly:
“Read-only”復選框是否可見。