如何将多个同扩展名文件移动至其他目录(含C#实现方案)
Got it, let's tackle both scenarios clearly—first how to handle this in a C# project, then general methods that work across different systems without needing a compiled app.
The key here is to first gather all files with your target extension, define your destination directories, then distribute and move the files accordingly. Here's a robust example with error handling and flexible distribution logic:
Example Code
using System; using System.IO; using System.Collections.Generic; class FileMover { static void Main(string[] args) { // 1. Configure your source path and target extension string sourceDir = @"C:\Your\Source\Directory"; string targetExtension = ".txt"; // Update to your desired extension // 2. List your destination directories (add as many as you need) List<string> destDirs = new List<string> { @"C:\Your\Dest\Dir1", @"C:\Your\Dest\Dir2", @"C:\Your\Dest\Dir3" }; // Make sure all destination folders exist foreach (string dir in destDirs) { if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); Console.WriteLine($"Created missing directory: {dir}"); } } // 3. Fetch and distribute files try { var files = Directory.EnumerateFiles(sourceDir, $"*{targetExtension}", SearchOption.TopDirectoryOnly); int dirIndex = 0; foreach (string file in files) { string fileName = Path.GetFileName(file); string destPath = Path.Combine(destDirs[dirIndex], fileName); // Skip files that already exist in the target (adjust if you want to overwrite/rename) if (File.Exists(destPath)) { Console.WriteLine($"Skipping {fileName} - already exists in {destDirs[dirIndex]}"); continue; } // Move the file File.Move(file, destPath); Console.WriteLine($"Moved {fileName} to {destDirs[dirIndex]}"); // Cycle through destination directories for even distribution dirIndex = (dirIndex + 1) % destDirs.Count; } } catch (Exception ex) { Console.WriteLine($"Error during file move: {ex.Message}"); } } }
Customization Tips
- Adjust distribution logic: The example cycles through directories one by one, but you could split files by size, filename hash, or even create new subdirectories dynamically for each file.
- Handle duplicates: The code skips existing files—you can modify it to rename duplicates (e.g.,
file_1.txt) or overwrite them if that's your requirement. - Include subfolders: Change
SearchOption.TopDirectoryOnlytoSearchOption.AllDirectoriesif you want to include files in nested source folders.
If you don't want to write compiled code, here are platform-specific methods to move files with the same extension to different directories:
Windows (PowerShell)
This script distributes .txt files evenly across three destinations. Tweak paths and extensions as needed:
$sourceDir = "C:\Your\Source\Directory" $destDirs = @("C:\Dest\Dir1", "C:\Dest\Dir2", "C:\Dest\Dir3") $extension = ".txt" # Create missing destination directories $destDirs | ForEach-Object { if (-not (Test-Path $_)) { New-Item -ItemType Directory -Path $_ } } $files = Get-ChildItem -Path $sourceDir -Filter *$extension -File $dirIndex = 0 foreach ($file in $files) { $destPath = Join-Path $destDirs[$dirIndex] $file.Name if (Test-Path $destPath) { Write-Host "Skipping $($file.Name) - already exists in target" continue } Move-Item -Path $file.FullName -Destination $destPath Write-Host "Moved $($file.Name) to $($destDirs[$dirIndex])" $dirIndex = ($dirIndex + 1) % $destDirs.Count }
Linux/macOS (Bash Script)
Save this as move_files.sh, make it executable with chmod +x move_files.sh, then run it:
#!/bin/bash SOURCE_DIR="/your/source/directory" DEST_DIRS=("/your/dest/dir1" "/your/dest/dir2" "/your/dest/dir3") EXTENSION=".txt" # Create destination directories if they don't exist for dir in "${DEST_DIRS[@]}"; do mkdir -p "$dir" done FILES=("$SOURCE_DIR"/*"$EXTENSION") DIR_INDEX=0 for file in "${FILES[@]}"; do if [ -f "$file" ]; then FILENAME=$(basename "$file") DEST_PATH="${DEST_DIRS[$DIR_INDEX]}/$FILENAME" if [ -f "$DEST_PATH" ]; then echo "Skipping $FILENAME - already exists in ${DEST_DIRS[$DIR_INDEX]}" continue fi mv "$file" "$DEST_PATH" echo "Moved $FILENAME to ${DEST_DIRS[$DIR_INDEX]}" DIR_INDEX=$(( (DIR_INDEX + 1) % ${#DEST_DIRS[@]} )) fi done
Windows Command Prompt (CMD)
For simple one-to-one moves (all files to a single directory), use this:
:: Move all .txt files from source to destination move "C:\Source\*.txt" "C:\Destination\"
Note: CMD lacks built-in logic for even distribution across multiple directories—use PowerShell for that scenario instead.
内容的提问来源于stack exchange,提问作者user9206489

