繁体   English   中英

如何从 OpenFileDialog 和 FolderBrowserDialog 获取文件路径?

[英]How to get file path from OpenFileDialog and FolderBrowserDialog?

嘿,几天前我开始学习 C#,我正在尝试制作一个将文件复制和粘贴(并在需要时替换)到选定目录的程序,但我不知道如何从打开文件对话框和文件夹浏览器对话框

我究竟做错了什么?

这是代码:

namespace filereplacer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void direc_Click(object sender, EventArgs e)
        {
            string folderPath = "";
            FolderBrowserDialog directchoosedlg = new FolderBrowserDialog();
            if (directchoosedlg.ShowDialog() == DialogResult.OK)
            {
                folderPath = directchoosedlg.SelectedPath;
            }
        }

        private void choof_Click(object sender, EventArgs e)
        {

            OpenFileDialog choofdlog = new OpenFileDialog();
            choofdlog.Filter = "All Files (*.*)|*.*";
            choofdlog.FilterIndex = 1;

            choofdlog.Multiselect = true;
            choofdlog.ShowDialog();
        }

        private void replacebtn_Click(object sender, EventArgs e)
        {
          // This is where i'm having trouble
        }

        public static void ReplaceFile(string FileToMoveAndDelete, string FileToReplace, string BackupOfFileToReplace)
        {
            File.Replace(FileToMoveAndDelete, FileToReplace, BackupOfFileToReplace, false);
        }
    }

对于OpenFileDialog

OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;

if (choofdlog.ShowDialog() == DialogResult.OK)    
{     
    string sFileName = choofdlog.FileName; 
    string[] arrAllFiles = choofdlog.FileNames; //used when Multiselect = true           
}

对于FolderBrowserDialog

FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Custom Description"; 

if (fbd.ShowDialog() == DialogResult.OK)
{
    string sSelectedPath = fbd.SelectedPath;
}

要访问selected folderselected file name您可以在类级别声明两个字符串。

namespace filereplacer
{
   public partial class Form1 : Form
   {
      string sSelectedFile;
      string sSelectedFolder;

      public Form1()
      {
         InitializeComponent();
      }

      private void direc_Click(object sender, EventArgs e)
      {
         FolderBrowserDialog fbd = new FolderBrowserDialog();
         //fbd.Description = "Custom Description"; //not mandatory

         if (fbd.ShowDialog() == DialogResult.OK)      
               sSelectedFolder = fbd.SelectedPath;
         else
               sSelectedFolder = string.Empty;    
      }

      private void choof_Click(object sender, EventArgs e)
      {
         OpenFileDialog choofdlog = new OpenFileDialog();
         choofdlog.Filter = "All Files (*.*)|*.*";
         choofdlog.FilterIndex = 1;
         choofdlog.Multiselect = true;

         if (choofdlog.ShowDialog() == DialogResult.OK)                 
             sSelectedFile = choofdlog.FileName;            
         else
             sSelectedFile = string.Empty;       
      }

      private void replacebtn_Click(object sender, EventArgs e)
      {
          if(sSelectedFolder != string.Empty && sSelectedFile != string.Empty)
          {
               //use selected folder path and file path
          }
      }
      ....
}

注意

因为你保持choofdlog.Multiselect=true; ,这意味着在OpenFileDialog()您可以选择多个文件(通过按ctrl键并单击鼠标左键进行选择)。

在这种情况下,您可以在string[]获取所有选定的文件:

在班级:

string[] arrAllFiles;

找到这一行(当Multiselect=true此行仅给出第一个文件):

sSelectedFile = choofdlog.FileName; 

要获取所有文件,请使用:

arrAllFiles = choofdlog.FileNames; //this line gives array of all selected files

使用System.IOPath类。 它包含用于操作文件路径的有用调用,包括GetDirectoryName ,它可以执行您想要的操作,返回文件路径的目录部分。

用法很简单。

string directoryPath = System.IO.Path.GetDirectoryName(choofdlog.FileName);

你可以将Path存储到字符串变量中

string s = choofdlog.FileName;

为了得到一个选定的文件或文件的完整的文件路径,那么你需要使用的FileName属性一个文件或文件名属性的多个文件。

var file = choofdlog.FileName; // for one file

或多个文件

var files = choofdlog.FileNames; // for multiple files.

要获取文件的目录,可以使用Path.GetDirectoryName
这是Jon Keet关于从路径获取目录的类似问题的答案

ShowDialog()返回后,您的choofdlog包含一个包含文件路径的FileNameFileNames (用于多选)。

将此类创建为Extension:

public static class Extensiones
{
    public static string FolderName(this OpenFileDialog ofd)
    {
            string resp = "";
            resp = ofd.FileName.Substring(0, 3);
            var final = ofd.FileName.Substring(3);
            var info = final.Split('\\');
            for (int i = 0; i < info.Length - 1; i++)
            {
                resp += info[i] + "\\";
            }
            return resp;
    }
}

然后,您可以这样使用:

        //ofdSource is an OpenFileDialog 
        if (ofdSource.ShowDialog(this) == DialogResult.OK)
        {
            MessageBox.Show(ofdSource.FolderName());
        }

一个原始的快速修复工作。

如果只使用OpenFileDialog ,则可以捕获FileNameSafeFileName ,然后减去获取文件夹路径:

exampleFileName = ofd.SafeFileName;
exampleFileNameFull = ofd.FileName;
exampleFileNameFolder = ofd.FileNameFull.Replace(ofd.FileName, "");

我很抱歉,如果我迟到在这里回复,但我只是认为我应该为OpenDialog提供一个更简单的解决方案。

OpenDialog ofd = new OpenDialog();
var fullPathIncludingFileName = ofd.Filename; //returns the full path including the filename
var fullPathExcludingFileName = ofd.Filename.Replace(ofd.SafeFileName, "");//will remove the filename from the full path

我之前还没有使用过FolderBrowserDialog所以我会相信我的同伴们对此有所了解。 我希望这有帮助。

String fn = openFileDialog1.SafeFileName;
String path = openFileDialog1.FileName.ToString().Replace(fn, "");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM