开发者

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

开发者 https://www.devze.com 2023-03-11 22:37 出处:网络
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.tx开发者_开发问答t \' (yes, with space at the

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.tx开发者_开发问答t ' (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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号