c#以相同的方法选择文件夹或文件

时间:2015-02-24 21:04:44

标签: c# .net openfiledialog folderbrowserdialog

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

我在这里搜索过,MSDN和其他互联网(其中大部分都指向这里)没有任何运气。我确实看到一个问题,询问使用OpenFileDialog选择文件夹而不是文件。我几乎可以肯定,我已经在主流应用程序中看到了这个问题,但这个问题被标记为过于含糊,而且在回复中没有得到解决。

我有一些需要文件/文件夹路径的文本框。我想简化处理这个问题的两种方法。唯一的区别是,一旦选择一个文件,另一个选择一个文件夹。为了简单和可读性,我想整合它们。

这是否可行,而不是将每个代码方法的内容放入一个大的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;
        }
    }

我已为每个Tag添加了TextBox,表明它是否需要文件或文件夹。我想使用Tag作为判断我是否应该使用文件或文件夹浏览器的条件。这是我无知所表现的地方;我曾设想过像这样的非工作代码:

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. 允许选择文件或文件夹的现有对象/方法,或
  2. 一种将对象动态重新定义为不同类型对象的方法
  3. 使用1方法根据调用对象上定义的某些OpenFileDialog动态允许使用FileBrowserDialogTag的任何其他方法。

4 个答案:

答案 0 :(得分:0)

尝试使用FolderBrowserDialogEx。

在这里查看详细解答: How do you configure an OpenFileDialog to select folders?

答案 1 :(得分:0)

这是我在不依赖第三方代码的情况下解决此问题的最简单方法,但您需要添加一些完整性检查,以防用户使用输入:

        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
            }
        }

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

答案 2 :(得分:0)

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

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

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;
}

您可以通过创建工厂类

来进一步推动它
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;
}

答案 3 :(得分:0)

为什么不尝试扩展TextBox类? 它很简单且可重复使用,您只需要将自定义控件拖放到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

*/