Home > Software design >  How to move files from subdirectory to directory above parent directory
How to move files from subdirectory to directory above parent directory

Time:11-16

I am trying to move all of the files and subdirectories from /XBLA/gameName/gameID/000D0000/ to /XBLA/gameName/ I have searched and tried the methods I've found but have not been able to make them work. I also need to be able to do this for all the different /gameName directories inside /XBLA/. Below is the code I have tried that does not work at all. I have tried some other combinations, but I can't remember them at the moment.

          static void MoveFiles()
                {
                string homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
                string unpackedPath = homePath   "\\XBLA_Unpacked\\";
                List<string> directoryName = Directory.GetFiles(unpackedPath, "000D0000", SearchOption.AllDirectories).ToList();
                List<string> destinationDirectory = Directory.GetFiles(unpackedPath, "*", SearchOption.TopDirectoryOnly).ToList();
                List<string> gameFiles = Directory.GetFiles(unpackedPath, "*", SearchOption.AllDirectories).ToList();
                foreach (string file in gameFiles)
                    {
                        File.Move(gameFiles.ToString(), destinationDirectory.ToString());                
                    }
                
                }

CodePudding user response:

The DirectoryInfo class can be helpful here. You can create one based on a string that represents the path, and then easily move directories and files.

Here's an example, but it would need some additional error handling for occasions where the source or destination directory don't exist:

public static void MoveFilesUpTwoDirectories(string sourceDir)
{
    var source = new DirectoryInfo(sourceDir);
    var dest = source.Parent.Parent;

    foreach(var subDir in source.GetDirectories())
    {
        subDir.MoveTo(Path.Combine(dest.FullName, subDir.Name));
    }

    foreach(var file in source.GetFiles())
    {
        file.MoveTo(Path.Combine(dest.FullName, file.Name));
    }
}

In use it would simply be:

string homePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string unpackedPath = Path.Combine(homePath, @"XBLA_Unpacked\000D0000");
MoveFilesUpTwoDirectories(unpackedPath);
  •  Tags:  
  • c#
  • Related