简体   繁体   中英

How to get file path from OpenFileDialog and FolderBrowserDialog?

Hey there i started learning C# a few days ago and I'm trying to make a program that copies and pastes files (and replaces if needed) to a selected directory but I don't know how to get the directory and file paths from the openfiledialog and folderbrowserdialog

what am I doing wrong?

Here's the code:

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

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

For FolderBrowserDialog :

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

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

To access selected folder and selected file name you can declare both string at class level .

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

NOTE :

As you have kept choofdlog.Multiselect=true; , that means in the OpenFileDialog() you are able to select multiple files (by pressing ctrl key and left mouse click for selection).

In that case you could get all selected files in string[] :

At Class Level:

string[] arrAllFiles;

Locate this line (when Multiselect=true this line gives first file only):

sSelectedFile = choofdlog.FileName; 

To get all files use this:

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

Use the Path class from System.IO . It contains useful calls for manipulating file paths, including GetDirectoryName which does what you want, returning the directory portion of the file path.

Usage is simple.

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

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

string s = choofdlog.FileName;

To get the full file path of a selected file or files, then you need to use FileName property for one file or FileNames property for multiple files.

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

or for multiple files

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

To get the directory of the file, you can use Path.GetDirectoryName
Here is Jon Keet's answer to a similar question about getting directories from path

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

Create this class as 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;
    }
}

Then, you could use in this way:

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

A primitive quick fix that works.

If you only use OpenFileDialog , you can capture the FileName , SafeFileName , then subtract to get folder path:

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

I am sorry if i am late to reply here but i just thought i should throw in a much simpler solution for the 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

I have not yet used a FolderBrowserDialog before so i will trust my fellow coders's take on this. I hope this helps.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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