C#  SaveFileDialog 设置多个Filter

1.示例使用FileDialogOpenFileDialog实现,并说明创建,设置属性和显示对话框。该示例使用FilterFilterIndex属性为用户提供过滤器列表。该示例需要一个上面放置有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属性设置哪个过滤选项首先显示给用户。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐