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

老子叫甜甜 提交于 2019-12-12 10:35:04

问题


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


回答1:


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).




回答2:


You can access the file with a illegal character after the space

C:\123.txt :illegal

The : and everything afterwards will be removed but the space will remain. You can also create files ending with a space this way.



来源:https://stackoverflow.com/questions/6274886/cant-copy-move-files-with-space-at-end-of-file-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!