这个问题有可能做的事实,你使用两种不同的方法.Substring
:String#Substring(int)
和String#Substring(int,int)
。确实:
File.Delete(filePath.Substring(filePath.Length - 4) + ".bak");
// ^with one int
File.Move(filePath, filePath.Substring(0, filePath.Length - 4) + ".bak");
// ^with two ints
不幸的是,这两者在语义上并不相同。 one with one int是开始索引。因此,鉴于filePath
等于test.txt
,您要删除的文件是.txt.bak
,接下来您的目标是将文件移动到test.bak
。或与Mono的C#模拟器运行以下命令:
csharp> String filePath = "test.txt";
csharp> filePath.Substring(filePath.Length - 4) + ".bak"
".txt.bak"
csharp> filePath.Substring(0, filePath.Length - 4) + ".bak"
"test.bak"
请更新:
File.Delete(filePath.Substring(0,filePath.Length - 4) + ".bak");
// ^added zero
File.Move(filePath, filePath.Substring(0, filePath.Length - 4) + ".bak");
另一种更优雅且不易出错的方式显然是使用一个变量之间,使得你确定,你在谈论同一个文件:
String backupfile = filePath.Substring(0, filePath.Length - 4) + ".bak";
File.Delete(backupfile);
File.Move(filePath,backupfile);
最后,不建议做通路处理自己:使用专用的方法来连结和操作文件路径。
我觉得FilePath在File.Delete方法中是不正确的。你能检查路径是否正确? – Baskar
尝试先移动文件,然后从原始位置删除最新的文件http://stackoverflow.com/questions/5704982/file-move-fails-when-preceded-by-a-file-delete – keyboardP