I am trying to move Txt files from one folder to another but I keep getting an error message stating "illegal characters in path". I think it's because of the * in the file name but how do i change it to except it?


string sourceFile = @"C:\\new1\*.txt";
string destinationFile = @"C:\\new2\*.txt";

Recommended Answers

All 4 Replies

File.Copy or File.Move only work on a single file; you cannot specify "*" to get all files.
If you want to move all files then you need to iterate through them manually:

DirectoryInfo source = new DirectoryInfo(@"C:\new1\");
DirectoryInfo destination = new DirectoryInfo(@"C:\new2\");

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

Brilliant, When I read up on it on the MSDN, it wasn't clear that it could be done only one file at a time. I thought I saw it on VB that this can be done but hey.

Thank you!

Firstly using the @ infront of a string will mean that the \\ is illegal.
Secondly, AFAIK none of the .Net file handling classes support wildcard characters in filenames so the * is also illegal.
Use Directory.GetFiles to get a String array of filenames. Then perform the move on each in turn using a for loop.

[Edit] Oh look Ryshad's already done it for you.

All file systems supported by Windows using the concept of files and directories to access data stored on a disk or device. Windows developers to work with the Windows API for file and device I / O must understand the various rules, conventions and limitations of file names and directories.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.