真的很疯狂!我使用Far 2.0创建了一个文件(http://www.farmanager.com/,也许你可以使用其他文件管理器); 它的文件名是'C:\ 123.txt' (是的,文件路径末尾有空格).
我正在尝试使用C#程序复制或移动此文件:
File.Copy("C:\\123.txt ", "C:\\456.txt", true);
Run Code Online (Sandbox Code Playgroud)
但它失败了"无法找到文件'C:\ 123.txt'." 例外.但文件存在!
我正在尝试Windows API:
[DllImport("kernel32.dll")]
public static extern int MoveFile(string lpExistingFileName, string lpNewFileName);
MoveFile("C:\\123.txt ", "C:\\456.txt",);
Run Code Online (Sandbox Code Playgroud)
但它也失败了.
我正在尝试xcopy实用程序:
C:\>xcopy "C:\123.txt " "C:\456.txt" /Y
File not found - 123.txt
0 File(s) copied
Run Code Online (Sandbox Code Playgroud)
如何以编程方式重命名文件?为什么会发生这种情况?
我的操作系统:Windows 7 x64
我使用下一个不安全的代码进行字符串修改:
public static unsafe void RemoveLastOne(ref string Str1)
{
if (Str1.Length < 1)
return;
int len = Str1.Length - 1;
fixed (char* pCh1 = Str1)
{
int* pChi1 = (int*)pCh1;
pCh1[len] = '\0';
pChi1[-1] = len;
}
}
Run Code Online (Sandbox Code Playgroud)
但是一段时间后我的C#programm崩溃了,例外:
FatalExecutionEngineError:"运行时遇到致命错误.错误地址为0x6e9a80d9,在线程0xcfc上.错误代码为0xc0000005.此错误可能是CLR中的错误或用户的不安全或不可验证部分此错误的常见来源包括COM-interop或PInvoke的用户封送错误,这可能会破坏堆栈."
如果我将函数"RemoveLastOne"更改为"Str1 = Str1.Remove(Str1.Length - 1);" 程序工作正常.
为什么发生异常?我如何正确地在C#中实现不安全的更改字符串?