gpt4 book ai didi

c# - 删除的文件还存在吗?

转载 作者:行者123 更新时间:2023-11-30 21:53:17 25 4
gpt4 key购买 nike

我正在尝试保存一些数据的备份。如果备份存在然后我想删除它,给最近的文件备份文件的名称,然后将新文件保存为最近的文件。

我遇到的问题是,当我删除一个现有文件时,我仍然无法以相同的名称保存另一个文件。系统仍然认为该文件存在,并且实际上在程序抛出异常时文件并没有被删除,即使这两行紧接在一起。我唯一能想到的是,“删除”操作在移动操作要执行时还没有时间完成。但我不知道如何修复它。

代码看起来像这样。

 File.Delete(filePath.Substring(filePath.Length - 4) + ".bak");
File.Move(filePath, filePath.Substring(0, filePath.Length - 4) + ".bak");

我想设置一个计时器以便稍后执行移动功能,但在我看来,这可能是一种非常草率和危险的处理问题的方式。此外,需要等待的时间可能因系统而异。所以我在想一定有更好的方法。

最佳答案

问题可能与您使用两种不同的.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);

最后不建议自己做路径处理:使用专门的方法加入和操作文件路径。

关于c# - 删除的文件还存在吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34006589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com