【问题标题】:How to limit which files should be shown in OpenFileDialog?如何限制应在 OpenFileDialog 中显示哪些文件?
【发布时间】:2013-12-07 09:11:42
【问题描述】:

我使用了这里的信息http://msdn.microsoft.com/ru-ru/library/system.windows.forms.openfiledialog(v=vs.110).aspx

这样:

Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

 dlg.DefaultExt = ".xml"; // this is how I get only required extension 
 dlg.Filter = "XML files (*.xml)|*.xml"; // I guess, this should be modified, don't know how.
dlg.InitialDirectory = _directoryName1;
// here we go
Nullable<bool> result = dlg.ShowDialog();
            if (result == true)
            {
                string path = dlg.FileName;

在初始目录中,我必须输入具有相同xml 扩展名的文件类型,其名称以script-Data...GeneralParam... 开头。所以我只需要在 OpenFileDialog 中显示名称以script-Data... 开头的文件。

我知道,我可以通过解析path 来通知用户他决定了错误的文件,但这对我来说不是一个好的解决方案。还有其他办法吗?

【问题讨论】:

    标签: c# winforms openfiledialog


    【解决方案1】:

    试试这个。它会对你有所帮助。如果你想过滤以“script-Data”开头的文件名,只能在你的应用程序中这样做。

    OpenFileDialog of = new OpenFileDialog();
    of.Filter = "Excel Files|script-Data*.xls;ascript-Data*.xlsx;script-Data*.xlsm";
    of.ShowDialog();
    

    【讨论】:

      【解决方案2】:

      您已经设置了Filter 属性。所以当OpenFileDialog 打开时,您只能看到.xml 文件。但是如果您想将filter filenames 显示在OpenFileDialog 中,则可以设置FileName 属性,因为filter 没有其他选项filename

      试试这个:

      dlg.FileName = "script-Data*";
      

      【讨论】:

        【解决方案3】:

        当然,您可以使用预期的预定义设置准备 OpenFileDialog,但是 您不能阻止您的用户在输入框中输入与预期模式完全不同的内容。例如,如果您的用户在输入框中键入 "*.*" 并按 OK,他/她可以选择显示的任何文件,但您可以检查已选择的内容 WITHOUT EXITING OpenFileDialog 并通知您的错误的用户。

        您只需订阅活动FileOk

        OpenFile dlg = new OpenFileDialog();
        dlg.FileOk += CheckFileName;
        dlg.InitialDirectory = _directoryName1;
        dlg.Filter = "XML Files (*.xml)|*.xml";
        dlg.FileName = "script-data*";
        if(sdlg.ShowDialog() == DialogResult.OK)
        { 
            Console.WriteLine("Open file:" + sdlg.FileName);
            ..... 
        }   
        
        
        
          void CheckFileName(object sender, System.ComponentModel.CancelEventArgs e)
          {
              OpenFileDialog dlg = (sender as OpenFileDialog);
              if(Path.GetExtension(dlg.FileName).ToLower() != ".xml")
              {
                  e.Cancel = true;
                  MessageBox.Show("Please choose files with the extension 'XML'");
                  return;
              }
              if(!Path.GetFileName(dlg.FileName).ToLower().StartsWith("script-data")
              {
                  e.Cancel = true;
                  MessageBox.Show("Please choose files that starts with 'script-data'");
                  return;
              }
           }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-06
          • 1970-01-01
          • 2016-06-14
          • 2019-09-27
          • 1970-01-01
          • 2016-08-31
          相关资源
          最近更新 更多