C# 自定义文件扩展名过滤器

C# custom file extension filter

我正在尝试读取目录中的文档列表。我了解过滤器修饰符如何在高层次上工作并且以前使用过它们。然而,这次我需要过滤一些没有标准化扩展名的东西(即“*.txt”或*.pdf”)。

我正在使用在...上找到的示例 https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.filedialog.filter?view=net-5.0

 using System;

using System.Windows.Forms;

namespace COMS2412_Readin
{
    public partial class Form1 : Form
    {
        string Serial_num = null;
        string INI_file_dir_temp = null;
        string CONFIG_data = null; 
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Allow user to enter serial number and load it for useage later. 
            Serial_num = Serial_number_text.Text;
            try
            {
                using (OpenFileDialog COMS_file_dialog = new OpenFileDialog())
                {
                    COMS_file_dialog.InitialDirectory = "c:\";
                    //Have dialog box filter out all files without the .INI extention. 
                    COMS_file_dialog.Filter = "txt files (*.INI)|*.INI|All files (*.*)|*.*"; //Failed
                    //                    COMS_file_dialog.Filter = "*.INI"; //Failed
                    //                    COMS_file_dialog.Filter = "(*.INI)"; //Failed
                    //                    COMS_file_dialog.Filter = "(INI files | *.INI)"; //Failed
                    COMS_file_dialog.FilterIndex = 2;
                    COMS_file_dialog.RestoreDirectory = true;
                    if (COMS_file_dialog.ShowDialog() == DialogResult.OK)
                    {
                        //Check to make sure it was the correct file type. 
                        INI_file_dir_temp = COMS_file_dialog.FileName;
                    }
                }
            }
            catch
            {
                //Sorry there was an error with opening the file. Please ensure the file is not currently open. 
            }
        }
    }
}

我正在处理的项目从外部设备导入配置文件。问题是实际上有数千个文件,每个文件都有不寻常的文件扩展名。例如 *.INI 是我要过滤的扩展名之一。我试过只输入 `*.INI 作为参数,但没有用。我错过了什么?有没有办法改变...

openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

过滤特定的文件扩展名?

最后,有一些有用的东西...

openFileDialog.Filter = "(*.INI)|*.INI";

这会过滤掉所有不属于 .INI 扩展名的内容。具体对我来说,我必须 运行 以管理员身份进行 VS 并确保文件未被隐藏。