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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With