Unable to copy / move files with space at end of file name

This is really crazy! I created the file using Far 2.0 ( http://www.farmanager.com/ , maybe you can use a different file manager); its file name: "C: \ 123.txt" (yes, with a space at the end of the file path) .

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 doesn’t work with “Could not find file“ C: \ 123.txt. ”Exception. But file exists!

I am trying to use the Windows API:

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

But it doesn’t work either.

And I'm trying to use the xcopy utility:

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

How can I rename a file programmatically? And why is this happening?

My OS: Windows 7 x64

+7
source share
2 answers

You have a character in the name of your file, which is illegal in Win32. To bypass the Win32 parser, you just need to specify the file name \\?\ . For example:

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

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

+10
source

After a space, you can access the file with an invalid character

 C:\123.txt :illegal 

The: and everything after that will be deleted, but the space will remain. You can also create files ending with a space.

0
source

All Articles