FileDialog.Filter 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得或設定目前的檔案名稱篩選字串,決定對話框中「另存為檔案類型」或「類型檔案」欄位中出現的選項。
public:
property System::String ^ Filter { System::String ^ get(); void set(System::String ^ value); };
public string Filter { get; set; }
member this.Filter : string with get, set
Public Property Filter As String
屬性值
對話框中提供的檔案篩選選項。
例外狀況
Filter 格式無效。
範例
以下程式碼範例使用 OpenFileDialog 了實作 FileDialog 並說明了建立、設定屬性及顯示對話框的過程。 範例中使用 和 FilterFilterIndex 屬性來提供使用者篩選條件清單。 這個範例需要一個表單上放置 a Button 並 System.IO 加上命名空間。
private:
void button1_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
{
Stream^ myStream;
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;
openFileDialog1->InitialDirectory = "c:\\";
openFileDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1->FilterIndex = 2;
openFileDialog1->RestoreDirectory = true;
if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK )
{
if ( (myStream = openFileDialog1->OpenFile()) != nullptr )
{
// Insert code to read the stream here.
myStream->Close();
}
}
}
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);
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myStream As Stream = Nothing
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
' Insert code to read the stream here.
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
End Sub
備註
每個過濾選項的濾波器字串包含濾波器的描述,接著是垂直條(|)和濾波器圖案。 不同過濾選項的字串由垂直條分隔。
以下是一個濾波器字串的範例:
Text files (*.txt)|*.txt|All files (*.*)|*.*
你可以透過分號分隔檔案類型,為過濾器添加多種過濾模式,例如:
Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*
使用屬性 FilterIndex 設定使用者首先顯示的過濾選項。