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

本文关键字:获取 文件 路径 FolderBrowserDialog OpenFileDialog | 更新日期: 2023-09-27 18:10:36

嘿,我开始学习c#几天前,我试图做一个程序,复制和粘贴文件(并替换如果需要)到一个选定的目录,但我不知道如何从openfiledialog和folderbrowserdialog

获得目录和文件路径

我做错了什么?

代码如下:

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和FolderBrowserDialog中获取文件路径

为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,可以在类级别声明这两个string

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.IO中的Path类。它包含了操作文件路径的有用调用,包括GetDirectoryName,它可以做你想做的事情,返回文件路径的目录部分。

用法简单。

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

您可以将Path存储到字符串变量中,如

string s = choofdlog.FileName;

要获得所选文件的完整文件路径,则需要对一个文件使用FileName属性,或对多个文件使用FileName属性。

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

或多个文件

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

要获得文件的目录,可以使用Path。GetDirectoryName
下面是Jon Keet对从路径

获取目录的类似问题的回答

创建这个类作为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());
        }

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

一个基本的快速修复。

如果你只使用OpenFileDialog,你可以捕获FileName, SafeFileName,然后减去得到文件夹路径:

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, "");