Question

I'm creating a C# windows based application which is basically a windows explorer modal. For copying and pasting folders from one place to another. Everything works fine. Here in my application i have two windows having a treeview each. The first one is the treeview which shows the location of the files which are to be copied and the second one is the treeview where the files are to be pasted.

Everything works fine, with the following code. Where i obtain all the files which are to be copied. All these files are copied to the clipboard.

string[] files = Directory.GetFiles(txtPath.Text.ToString(), "*.*", SearchOption.TopDirectoryOnly);
//also tried using SearchOption.AllDirectories
if (files != null)
{
     IDataObject data = new DataObject(DataFormats.FileDrop, files);
     MemoryStream memo = new MemoryStream(4);
     byte[] bytes = new byte[] { (byte)(copy_cut ? 2 : 5), 0, 0, 0 };
     memo.Write(bytes, 0, bytes.Length);
     data.SetData("Preferred DropEffect", memo);
     Clipboard.SetDataObject(data);
}

And are pasted into the respective folder using the following code

IDataObject data = Clipboard.GetDataObject();
if (!data.GetDataPresent(DataFormats.FileDrop))
     return;

     string[] files = (string[])data.GetData(DataFormats.FileDrop);
     MemoryStream stream = (MemoryStream)data.GetData("Preferred DropEffect", true);
     int flag = stream.ReadByte();
     if (flag != 2 && flag != 5)
         return;
     bool cut = (flag == 2);
     foreach (string file in files)
     {
         string dest = "C:" + "\\" + System.IO.Path.GetFileName(file);
         try
         {
             if (cut)
                File.Move(file, dest);
             else
                File.Copy(file, dest, false);
         }
         catch (IOException ex)
         {

         }
      }

Everything works fine for me. The copying and Pasting are good. But only for a folder which doesnt have any subfolder.

If i happen to have many folders inside a single folder and each folder having many files. Then this above code doesnt work properly.

eg.

If folder A has subfolders X,Y,Z and each subfolder X,Y,Z has many files, when i copy to the clipboard and paste to the desired location, i get only the contents/files of the folders X,Y,Z and not the folders X,Y,Z itself.

Is there a way that i can copy the folder X,Y,Z to the Clipboard and paste them as well. Just like the simple copy and paste that we do in a PC and the whole folder along with the subfolders are pasted in the desired location.

Help related to this issue would be really appreciated.

Thanks,

Vikneshwar

Was it helpful?

Solution

If you want to copy and keep the same structure intact you'll have to create a recursive function.

Msdn has an example of this which you can find here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top