LitteringAnd
LitteringAnd

Reputation: 69

Moving multiple files with openfiledialog

I'm trying to move multiple files to another directory in an openfiledialog box while preserving the file name. I'm having trouble doing it with more than one file and created a string array and a foreach loop. Below is the code. I tried to loop the array (i++, etc.) but kept getting a 'cannot find string[]' error. Basically it does ok with the first file but then it wants to keep moving the same file over to the other directory. It doesn't move down the list of selected files to move them. I tried 'System.IO.File.Move' with the same results. I realize this code below is shoddy.

string [] MoveFrom = openFileDialog1.FileNames;

string [] FileName = openFileDialog1.SafeFileNames;

string MoveTo = "C://Users//Kevin//Desktop//Archive";

        foreach (string files in MoveFrom)
                {
                  foreach (string files2 in FileName)
                    {
                      Directory.Move(MoveFrom, MoveTo + "//" + FileName)                                       
                     }
                 }

Upvotes: 1

Views: 1711

Answers (2)

Roman Marusyk
Roman Marusyk

Reputation: 24579

First, you have to set the property Multiselect of openFileDialog to true. Then you will access the FileNames property. After that you can use only on foreach loop to moving files.

About exception: you try to pass an array MoveFrom to method Move() :

Directory.Move(MoveFrom, MoveTo + "//" + FileName)

but according to syntax of this method there have to be string variable:

public static void Move(string sourceDirName, string destDirName)

In foreach you should to use loop's variable. Also I prefer to use Path.Combine() to prevent trouble with '\' and Path.GetFileName() to get file's name with extension

Please try something like this:

 openFileDialog1.Multiselect = true;
 if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
 {
   string[] MoveFrom = openFileDialog1.FileNames;
   string MoveTo = "C://Users//Kevin//Desktop//Archive";

   foreach (string files in MoveFrom)
   {
        Directory.Move(files, Path.Combine(MoveTo, Path.GetFileName(files)));                                                     
   }
 }

Upvotes: 2

Fᴀʀʜᴀɴ Aɴᴀᴍ
Fᴀʀʜᴀɴ Aɴᴀᴍ

Reputation: 6251

This should work:

string MoveTo = "D:\\"; //Change to your path
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        foreach (string _file in openFileDialog1.FileNames)
        {
            FileInfo fi = new FileInfo(_file);
            File.Move(_file, Path.Combine(MoveTo, fi.Name));
        }
    }

Upvotes: 3

Related Questions