OpenFileDialog() - 如何根据文件过滤器设置MultiSelect选项?

时间:2016-02-23 11:07:48

标签: c# openfiledialog

OpenFileDialog() - 如何根据文件过滤器设置MultiSelect选项?

我的OpenFileDialog可以选择2种类型的文件。这是使用的过滤器:

“LFA或日志文件(.lfa,。log)| .lfa; .log”

将MultiSelect属性设置为false。

新要求更改是:应允许用户选择多个日志文件,但只能选择一个LFA文件。

如果我将MultiSelect设置为true,它将允许选择多个log和lfa文件。

请告知有没有办法实现此功能?

2 个答案:

答案 0 :(得分:1)

在您的回答之后,如果您不希望文件对话框的UI关闭并重新打开,您实际上可以这样做。拥有IsValidFileSelection,应该是这样做的事情:

dlgFileBrowse.FileOk += (s,e) => {
   var dlg = s as OpenFileDialog;
   if (dlg == null) return;
   if (!IsValidFileSelectiom(dlg.FileNames))
   {
      // Or whatever
      MessageBox.Show("Please select one log/lfa file or multiple log files.");
      e.Cancel = true;
   }         
};

在致电OpenDialog()

之前

答案 1 :(得分:0)

这就是现在处理要求的方式。

        // Set filter for file extension and default file extension
        dlgFileBrowse.DefaultExt = ".log";
        dlgFileBrowse.Filter = "LFA or log files (.lfa, .log)|*.lfa;*.log";
        dlgFileBrowse.Title = "Select one LFA/Log file or multiple log files.";
        dlgFileBrowse.InitialDirectory = UserSettingsHelper.GetLastBrowsedPath();
       // Allow user to select multiple log files.
        dlgFileBrowse.Multiselect = true;

这就是我调用OpenBrowse对话框的方式。

if (dlgFileBrowse.ShowDialog() == DialogResult.OK)
        {
            // Validate the file selection.
            if (IsValidFileSelectiom(dlgFileBrowse.FileNames))
            {
                // Processing my files here.
            }
            else
            {
                // Display selection criterion.
                this.UiMessage = "Please select one log/lfa file or multiple log files.";
            }
        }

验证以下面的单独方法处理。

public bool IsValidFileSelection(string[] fileNames)
    {
        bool isValid = false;

        // There is no need to check the file types here.
        // As it is been restricted by the openFileBrowse

        if (fileNames != null && fileNames.Count() > 0)
        {
            if (fileNames.Count() == 1) // can be one .lfa file of one .log file
            {
                isValid = true;
            }
            else
            {
                // If multiple files are there. none shoulf be of type .lfa
                isValid = ! fileNames.Any( f => Path.GetExtension(f) == IntegoConstants.Lfa_Extension);
            }
        }

        return isValid;
    }

这涉及到最终用户的往返。如果可以在OpenFileDialog中完成此验证,那会更好。但不幸的是,我没有看到任何解决方法。