Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't copy/move files with space at end of file name

It's really crazy! I have created a file using Far 2.0 (http://www.farmanager.com/, maybe you can use some other file manager); its filename is 'C:\123.txt ' (yes, with space at the end of filepath).

And I'm trying to copy or move this file using a C# program:

File.Copy("C:\\123.txt ", "C:\\456.txt", true);

But it fails with the "Could not find file 'C:\123.txt '." exception. But the file exists!

I'm trying the Windows API:

[DllImport("kernel32.dll")]
public static extern int MoveFile(string lpExistingFileName, string lpNewFileName);
MoveFile("C:\\123.txt ", "C:\\456.txt",);

But it fails too.

And I'm trying the xcopy utility:

C:\>xcopy "C:\123.txt " "C:\456.txt" /Y
File not found - 123.txt
0 File(s) copied

How can I can rename the file programmatically? And why does this happen?

My OS: Windows 7 x64

like image 786
Ilya Georgievsky Avatar asked Feb 02 '23 17:02

Ilya Georgievsky


1 Answers

You have a character in your filename that's illegal in Win32. To circumvent the Win32 path parser, you just have to prefix your filename with \\?\. For example:

MoveFile(@"\\?\C:\123.txt ", "C:\\456.txt");

This technique will also allow you to have paths up to 32k in length (you only get 260 including the drive letter in Win32).

like image 132
Gabe Avatar answered Feb 06 '23 14:02

Gabe