WinForm 文件夹和文件选择对话框

来源:互联网 发布:加入域找不到网络名 编辑:程序博客网 时间:2024/05/16 13:43

1.文件选择对话框,选择多个文件并绑定ListBox
    private void SelectMultiFile()
    {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true; //可以选择多个文件
            fileDialog.Filter = "GeoMap图件|*.gdb|所有文件|*.*";
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                ArrayList fileList = new ArrayList();

                foreach (string file in fileDialog.FileNames)
                {
                    FileInfo info = new FileInfo(file.Substring(file.LastIndexOf("\\") + 1), file);
                    fileList.Add(info);
                }
                listBoxSelectedFile.DataSource = fileList;
                listBoxSelectedFile.DisplayMember = "FileName";
                listBoxSelectedFile.ValueMember = "FileFullName";
            }
     }

public class FileInfo
{
    private string _FileName;
    private string _FileFullName;

    public FileInfo(string fileName, string fileFullName)
    {
        _FileName = fileName;
        _FileFullName = fileFullName;
    }

    public string FileName
    {
        get { return _FileName; }
        set { _FileName = value; }
    }

    public string FileFullName
    {
        get { return _FileFullName; }
        set { _FileFullName = value; }
    }
}

2.文件夹选择对话框
要实现文件夹对话框,需要继承FolderNameEditor类,创建FolderBrowser类的实例。
引用System.Design.dll,using System.Windows.Forms.Design,代码如下:
public class FolderDialog : FolderNameEditor
    {
        FolderBrowser fDialog = new FolderBrowser();

        public FolderDialog()
        {
        }

        public DialogResult DisplayDialog()
        {
            return DisplayDialog("请选择保存位置");
        }

        public DialogResult DisplayDialog(string description)
        {
            fDialog.Description = description;
            return fDialog.ShowDialog();
        }

        public string Path
        {
            get { return fDialog.DirectoryPath; }
        }

        ~FolderDialog() { fDialog.Dispose(); }
    }


调用:
            string savePath="";
            FolderDialog folder = new FolderDialog();
            if (folder.DisplayDialog() == DialogResult.OK)
            {
                savePath = folder.Path;
            }
            else
            {
                return;
            }