Search code examples
c#filesystem.io.filesystem.io.directory

How do I move all the file paths in an array to one directory


This is what I have tried

string[] filestomove = new string[] {"text.txt", "never.json", "gonna.dll", "giveyou.exe", "up.png"};
string[] dirstomove = new string[] {"never gonna", "let you down", "never gonna", "run around", "and desert you"};
foreach(string filename in filestomove)
{
    if(File.Exists(filename)) {
        File.Copy(filename, path, true);
    }
}

foreach(string dirname in dirstomove)
{
    if(Directory.Exists(dirname)) {
        Directory.Move(dirname, path);
    }
}

However, it didnt work for me for some reason, it gave me an error. Does anyone know how to do this?


Solution

  • You need to specify a full path to write to:

    string[] filestomove = new string[] {"text.txt", "never.json", "gonna.dll", "giveyou.exe", "up.png"};
    string[] dirstomove = new string[] {"never gonna", "let you down", "never gonna", "run around", "and desert you"};
    foreach(string filename in filestomove)
    {
        if(File.Exists(filename)) 
        {
            // from c:\folder\A.txt, extract A.txt
            string name = Path.GetFileName(filename);
    
            // combine that with path to get c:\newfolder\A.txt
            string targetFileName = Path.Combine(path, name);
         
            // Move the file
            File.Copy(filename, targetFileName, true);
        }
    }
    
    foreach(string dirname in dirstomove)
    {
        if(Directory.Exists(dirname)) 
        {
            // From c:\folder\somefolder get somefolder
            string name = new DirectoryInfo(dirname).Name;
            
            // Combine that with path to get c:\newfolder\somefolder
            string targetDirectory = Path.Combine(path, name);
    
            // Move the directory
            Directory.Move(dirname, targetDirectory);
        }
    }