Click here to Skip to main content
15,919,422 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to move files from one folder to another. Can anyone tell me what is wrong with this code.

DirectoryInfo dir1 = new DirectoryInfo(@"C:\Users\Test\Testing.txt");
DirectoryInfo dir2 = new DirectoryInfo(@"C:\Users\Test2");

FileInfo[] Folder1Files = dir1.GetFiles();
if (Folder1Files.Length > 0)
{
   foreach (FileInfo aFile in Folder1Files)
   {
     if (File.Exists(dir2 + aFile.Name))
     {
         File.Delete(dir2 + aFile.Name);
     }
     aFile.MoveTo(dir2 + aFile.Name);
   }
}

When I run this code nothing happens. Any help will be appreciated.
Posted
Updated 14-Oct-10 3:23am
v2

1 solution

Your dir1 is not actually a directory... I mean it could be but it really looks like a text file.

I am guessing you want to do this:

DirectoryInfo dir1 = new DirectoryInfo(@"C:\Users\Test");
DirectoryInfo dir2 = new DirectoryInfo(@"C:\Users\Test2");
FileInfo[] Folder1Files = dir1.GetFiles();
if (Folder1Files.Length > 0)
{
    foreach (FileInfo aFile in Folder1Files)
    {
       if (File.Exists(dir2.Name + aFile.Name))
       {
           File.Delete(dir2.Name + aFile.Name);
       }
       aFile.MoveTo(dir2.Name + aFile.Name);
    }
}


Note: I also added ".Name" to your directory info objects. This pulls the directory name rather than a direct ToString. Not sure what the direct ToString gets you but .Name is what you should use.
 
Share this answer
 
v3
Comments
Neil Cross 14-Oct-10 9:20am    
Thanks it's always something simple.
[no name] 14-Oct-10 9:22am    
Np. Please click accept answer if it suffices.
Dalek Dave 14-Oct-10 9:25am    
I spotted that, but you beat me to it!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900