C# OpenFileDialog可以按名称过滤某些文件吗?

C# OpenFileDialog可以按名称过滤某些文件吗?,c#,.net,filter,showdialog,fileopendialog,C#,.net,Filter,Showdialog,Fileopendialog,首先,我已经看了这个。其中一个答案似乎为在ShowDialog中按名称过滤提供了希望。现在,以下是我尝试做的描述: 我有一段C代码: private System.Windows.Forms.OpenFileDialog csv_file_open_dlg; . . . csv_file_open_dlg.FileName = ""; csv_file_open_dlg.Filter = "csv files (*.csv)|*.csv|All files

首先,我已经看了这个。其中一个答案似乎为在ShowDialog中按名称过滤提供了希望。现在,以下是我尝试做的描述:

我有一段C代码:

private System.Windows.Forms.OpenFileDialog csv_file_open_dlg;
.
.
.
  csv_file_open_dlg.FileName = "";
  csv_file_open_dlg.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
  int rc = 0;


  if (csv_file_open_dlg.ShowDialog() == DialogResult.OK)
  {
     if (0 == m_csv_file_cmp_counter)
     {
        m_firstCsvFileSelected = csv_file_open_dlg.FileName;
     }
.
.
.
如果我选择第一个文件-May 18 Muni RosterDetailReport.csv-并将其名称保留在字符串变量中,是否有方法在下次ShowDialog在同一目录中运行时过滤掉该文件

换句话说,在选择5月18日的Muni RosterDetailReport.csv后,是否有办法将该名称作为过滤器反馈回ShowDialog

我想答案是否定的,但我只是再核实一下。如果没有,是否有一种解决方法,如我在本文开头提到的文章中所述,订阅OpenFileDialog事件

编辑:
听起来,我可以使用OK事件来防止用户再次选择第一个文件?我希望有人能回答这个问题。

鉴于在OpenFileDialog中无法按文件名进行筛选,我这样做是为了防止用户加载同一文件两次:

string m_firstFileLoaded; // a member variable of the class.
.
.
.
private void LoadCsvFile_Click(object sender, EventArgs e)
{
    printb.Enabled = false;
    csv_file_open_dlg.FileName = "";
    csv_file_open_dlg.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
    int rc = 0;

    if (csv_file_open_dlg.ShowDialog() == DialogResult.OK)
    {
        if (0 == m_csv_file_cmp_counter)
        {
            m_firstFileLoaded = csv_file_open_dlg.FileName;
            m_ComparisionDirection = -1; // Resets first and second file toggling.
            m_csv_file_cmp_counter = 0;
            m_csv_file_first.set_csv_path(csv_file_open_dlg.FileName);
            rc = m_csv_file_first.map_csv();
            LoadCsvFile.Text = "Load next csv file";
            m_csv_file_cmp_counter++;
        }
        else
        {
            // If the file is already chosen, throw up a warning.
            if (0 == String.Compare(m_firstFileLoaded, csv_file_open_dlg.FileName))
            {
                MessageBox.Show("You have already loaded " + csv_file_open_dlg.FileName + " . Please select another file", "Attempt to reload first file", MessageBoxButtons.OK);
            }
            else
            {

                m_csv_file_next.set_csv_path(csv_file_open_dlg.FileName);
                rc = m_csv_file_next.map_csv();
                LoadCsvFile.Text = "Files loaded.";
                LoadCsvFile.Enabled = false;
                start_compare.Enabled = true;
            }
        }
    }
}

你试过把这个字符串放在Filter属性中吗?@KennethK。Fliter属性仅适用于文件扩展名,而不适用于文件名。这是不可能的。您可以使用FileOk事件阻止用户选择文件。另一种完全不同的方法是在处理文件后将其移动到不同的目录中。做一件非常明智的事情,也会使清理变得更加容易。@Lewsterin我已经有一段时间没有做WinForms了……记不得了:@HansPassant,我可以完成我想做的事情。所以,如果你想回答这个问题,这是一个很好的答案。