C# SaveFileDialog 設置多個Filter
1.示例使用FileDialog的OpenFileDialog實現,並說明創建,設置屬性和顯示對話框。該示例使用Filter和FilterIndex屬性爲用戶提供過濾器列表。該示例需要一個上面放置有Button的窗體,並在其中添加System.IO命名空間。
public string Filter { get; set; }
var fileContent = string.Empty;
var filePath = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
filePath = openFileDialog.FileName;
//Read the contents of the file into a stream
var fileStream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
fileContent = reader.ReadToEnd();
}
}
}
MessageBox.Show(fileContent, "File Content at path: " + filePath, MessageBoxButtons.OK);
對於每個過濾選項,過濾器字符串均包含過濾器的說明,後跟豎線(|)和過濾器圖案。不同過濾選項的字符串由豎線分隔。
以下是過濾器字符串的示例:
Text files (*.txt)|*.txt|All files (*.*)|*.*
您可以通過使用分號分隔文件類型來向過濾器添加多個過濾器模式,例如:
Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*
使用FilterIndex屬性設置哪個過濾選項首先顯示給用戶。