c# select 文件夹或文件同方法

c# select Folders or Files in the same method

好的,所以请不要对我太过火,这是我在这里的第一个问题,也许我想做的事情甚至是不可能的。显然我不是专家;这就是我来找你的原因。 :)

我在这里、MSDN 和 Internet 的其余部分(其中大部分指向此处)都进行了搜索,但没有任何运气。我确实看到一个问题询问关于使用 OpenFileDialog 到 select 文件夹而不是文件。我几乎可以肯定我在主流应用程序中看到过这个问题,但是这个问题被标记为过于模糊,并且在回复中没有解决这个特别的警告。

我有一些文本框需要 file/folder 路径。我想将处理此问题的两种方法简化为一种。唯一的区别是,一次 select 是一个文件,而另一个 select 是一个文件夹。为了简单和可读性,我想合并它们。

这样可以吗,不用字面意思把每个代码方法的内容放到一个大的IF中?

以下是两种方法:

private void FolderBrowser(object sender, EventArgs e)
    {
        TextBox SenderBox = sender as TextBox;
        if (SenderBox.Text != "")//if the text box is not empty
        {
            //set the selected path to the text box's current contents (incase of accidental entry)
            FileBrowserDialog.FileName = SenderBox.Text;
        }
        if (FileBrowserDialog.ShowDialog() == DialogResult.OK)
        {
            SenderBox.Text = FileBrowserDialog.FileName;
        }
    }

private void FileBrowser(object sender, EventArgs e)
    {   //basically the same as the folder browser above, but for selecting specific files
        TextBox SenderBox = sender as TextBox;
        if (SenderBox.Text != "")//if the text box is not empty
        {
            //set the selected path to the text box's current contents (incase of accidental entry)
            FileBrowserDialog.FileName = SenderBox.Text;
        }
        if (FileBrowserDialog.ShowDialog() == DialogResult.OK)
        {
            SenderBox.Text = FileBrowserDialog.FileName;
        }
    }

我在每个 TextBox 中添加了一个 Tag,表明它是否需要文件或文件夹。我想使用 Tag 作为我确定是否应该使用文件或文件夹浏览器的条件。这就是我无知的地方;我曾设想过类似这样的 NONWORKING 代码:

private void browser(object sender, EventArgs e)
    {
        //cast sender as a textbox
        TextBox tBox = (TextBox)sender;
        object browser = null;

        if (tBox.Tag.ToString().Equals("Folder"))
        {
            browser = new FolderBrowserDialog();
        }
        else
        {
            browser = new OpenFileDialog();                
        }

        if (tBox.Text != "")//if the text box is not empty
        {
            //set the selected path to the text box's current contents (incase of accidental entry)
            browser.FileName = tBox.Text;
        }
        if (browser.ShowDialog() == DialogResult.OK)
        {
            tBox.Text = browser.FileName;
        }
    }

我是疯了,还是有办法实现我的想法?明确一点,我想知道是否有:

  1. 允许 select 文件或文件夹的现有 Object/Method,或
  2. 一种将对象动态重新定义为不同类型对象的方法
  3. 使用 1 方法的任何其他方式动态允许使用 OpenFileDialogFileBrowserDialog 基于调用对象上定义的某些 Tag

尝试使用 FolderBrowserDialogEx。

在此处查看详细答案: How do you configure an OpenFileDialog to select folders?

这是我发现的无需依赖第三方代码即可解决此问题的最简单方法,但您需要添加一些合理性检查,以防用户输入错误:

        OpenFileDialog ofd = new OpenFileDialog();
        ofd.CheckFileExists = false;
        string defaultFilename = "Select this folder";
        ofd.FileName = defaultFilename;

        if (ofd.ShowDialog().Value)
        {
            // Check if the user picked a file or a directory, for example:
            if (!ofd.FileName.Contains(defaultFilename))
            {
                // File code
            }
            else // You should probably turn this into an else if instead
            {
                // Directory code
            }
            // Alternatively, but still as unsafe
            if (File.Exists(ofd.FileName))
            {
                // File code
            }
            else
            {
                // Directory code
            }
        }

基本上,这里的"trick"就是将OpenFileDialog的CheckFileExists设置为false。

两个对话框(FileOpenDialogFolderBrowserDialog)都继承自 CommonDialog;但是,这个基 class 没有 属性 来检索结果。此外,属性 在两个对话框中的命名不同。

您可以通过创建包装器来解决问题。继承是将对象重新定义为不同类型的正确方法。

public abstract class FileFolderDialogBase
{
    public abstract bool ShowDialog();
    public string Result { get; protected set; }
}

public class FileDialog : FileFolderDialogBase
{
    public override bool ShowDialog()
    {
        var ofd = new OpenFileDialog();
        if ofd.ShowDialog() == DialogResult.OK) {
            Result = ofd.FileName;
            return true;
        }
        return false;
    }
}

public class FolderDialog : FileFolderDialogBase
{
    public override bool ShowDialog()
    {
        var fbd = new FolderBrowserDialog();
        if (fbd.ShowDialog() == DialogResult.OK)
            Result = fbd.SelectedPath;
            return true;
        }
        return false;
    }
}

用法:

var dialog = textBox.Tag == "Folder" ? new FolderDialog() : new FileDialog;
if (dialog.ShowDialog()) {
    textBox.Text = dialog.Result;
}

您可以通过创建工厂进一步推动它 class

public static class FileFolderDialog
{
    public static FileFolderDialogBase Create(string type)
    {
        swich (type.ToLowerInvariant()) {
            case "folder":
            case "dir":
            case "directory":
                return new FolderDialog();
            default:
                return new FileDialog();
        }
    } 
}

用法

var dialog = FileFolderDialog.Create(textBox.Tag);
if (dialog.ShowDialog()) {
    textBox.Text = dialog.Result;
}

为什么不尝试扩展 TextBox Class? 它简单且可重复使用,您只需将自定义控件拖放到 WinForm

    class FileTextBox : System.Windows.Form.TextBox{
       //===>This enumeration is more readable insted of a string XD
       public enum DialogType{
         File,Folder
       }
     //===>This property we will handle what kind of Dialog to show
    public DialogType OpenDialogType{
      get;
      set;
    }

    //===>This is where Object Oriented Programming a& Design do his magic
    public System.Windows.Forms.DialogResult ShowDialog(string Title =""){
      //===>This function is where we define what kind of dialog  to show
      System.Windows.Forms.DialogResult Result =   System.Windows.Forms.DialogResult.None ;
      object Browser=null;

           switch(this.OpenDialogType){
                  case DialogType.File:
                  Browser = new OpenFileDialog();
                  ((Browser)OpenFileDialog).Title= Title;
                   if(this.Text.Trim() !="" && this.Text != null ){
                     ((Browser)OpenFileDialog).FileName = this.Tex;
                   }
                  Result = ((Browser)OpenFileDialog).ShowDialog();

                  break;

                  case DialogType.Folder:
                  Browser = new FolderBrowserDialog ();
                  ((Browser)FolderBrowserDialog).Description = Title;

                  if(this.Text.Trim() !="" && this.Text != null ){
                      ((Browser)FolderBrowserDialog).RootFolder = this.Text; 
                  } 

                  Result = ((Browser)FolderBrowserDialog).ShowDialog();
                  break;
           }
    return Result;//===>We return thi dialog result just if we want to do something else
    }

}
/*
Create a class and copy/paste this code, I think is going to work because
I didn't compiled then go to ToolBox window find this control and Drag & Drop
to your WinForm and in the property window find OpenDialogType property
and this is where you kind define the behavior of OpenDialog();

I'm currently working in a little project in Vs where I create a custom
UI Control downloaded from my git repository 

https://github.com/MrAlex6204/GYMSystem

*/