Ben Bagi Ben Bagi - 2 months ago 13
C# Question

File moving in C#

I'm trying to write a simple file mover in C# to move my converted ebooks. The compilation gets done without errors, whenever I'm running the application, however gives the following error message: illegal characters in path.

My code is the following:

namespace EbookMover2
class Program
static void Main(string[] args)
string sourceFile = @"C:\Users\Ben\Documents\Calibre Library\*.azw3";
string destinationFile = @"F:\Downloads\dns\Ebooks\tocopy\*.azw3";

System.IO.File.Move(sourceFile, destinationFile);

I've used the @ character especially to prevent this problem. What could cause this?
Another question: how could I add another extension? Say, move .azw3 and .mobi files.
I'm a total newbie in C#, please bear this in mind when answering. :) Thanks in advance!


You cannot have the character * in a file path, and the Move method is meant to move one file at a time with an explicit file path (i.e. with no wildcards).

If you're trying to move multiple files that match a pattern, you can use Directory.GetFiles(string, string) with your search pattern as the second argument containing your wildcard, and then loop through each file and move it individually.

string sourceFolderPath = @"C:\Users\Ben\Documents\Calibre Library";
string filePattern = @"*.azw3";
string destinationFolderPath = @"F:\Downloads\dns\Ebooks\tocopy";
string[] matchingFiles = Directory.GetFiles(sourceFolderPath, filePattern);

foreach(string filePath in matchingFiles)
    var fileSpec = new FileInfo(filePath);
    File.Move(filePath, Path.Combine(destinationFolderPath, fileSpec.Name));