Search code examples
windowsfilemove

Script to move files from folder to another folder using paths in text file


On Windows 8, could someone please help me create a script to move some images from a particular folder to another folder?

The file path that lists the images i want to move (not all images) from the folder are listed in this file: C:\Users\Emmanuel\Desktop\test.txt

The folder in which contains some of the images I want removed appear in this folder:

C:\Users\Computer\Desktop\Images1

The folder in which I want the images to be moved to is this folder:

C:\Users\Computer\Desktop\Images2

Your help will be much appreciated


Solution

  • Try this where SourcesFile is your test.txt and DestFolder is the destination.

        public int Run()
        {
            if (!File.Exists(SourcesFile))
            {
                throw new ArgumentException("Source folder does not exist");
            }
    
            if (!Directory.Exists(DestFolder))
            {
                Console.WriteLine("Destination folder doesn't exist");
                Console.WriteLine("Creating destination folder...");
                Directory.CreateDirectory(DestFolder);
            }
    
            string[] files = File.ReadAllLines(SourcesFile);
            Console.WriteLine("Moving {0} files...", files.Length);
            foreach (string file in files)
            {
                string dest = Path.Combine(DestFolder, Path.GetFileName(file));
                if (File.Exists(dest))
                {
                    string newFilename = string.Format("{0}_{1}{2}",
                        Path.GetFileNameWithoutExtension(file),
                        Guid.NewGuid().ToString("N"),
                        Path.GetExtension(file));
    
                    string newDest = Path.Combine(DestFolder, newFilename);
                    Console.WriteLine("File {0} already exists, copying file to {1}", file, newDest);
                    File.Move(file, newDest);
                    continue;
                }
                File.Move(file, dest);
            }
            return 0;
        }