模仿File.Move如果目标已经存在 [英] Mimic File.Move if the destination already exists

查看:483
本文介绍了模仿File.Move如果目标已经存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

File.Move

请注意,如果您试图通过移动同名的文件到替换文件该目录,你会得到一个IOException。您不能使用Move方法来覆盖现有文件。

Note that if you attempt to replace a file by moving a file of the same name into that directory, you get an IOException. You cannot use the Move method to overwrite an existing file.

在总之,你不能覆盖在移动,所以为了方便覆盖上移我做一个 File.Copy 后跟一个文件模仿行为.Delete 。是这样的:

In short, you can't overwrite on Move, so in order to facilitate overwriting on Move I mimic the behavior by doing a File.Copy followed by a File.Delete. Something like:

if (File.Exists(dstFileName))
{
    // System.IO.File.Move cannot be used to overwrite existing files, so we're going
    // to simulate that behavior with a Copy & Delete.
    File.Copy(procContext.FileName, dstFileName);
    File.Delete(procContext.FileName);
}
else
    File.Move(procContext.FileName, dstFileName);



我的问题是:是否有我需要警惕,任何情况下,可能导致源文件没有它首先被成功地复制被删除?

My question is: Are there any situations that I need to guard against which could lead to the source file being deleted without it first being successfully copied?

我从阅读文档的理解是,因为 File.Copy 不返回任何东西,它应该抛出除了在任何情况下,它不会成功。有没有人遇到过这是不是真的任何情况呢?

My understanding from reading the documentation is that since File.Copy doesn't return anything that it should throw an exception in any case that it doesn't succeed. Has anyone encountered any situations where this isn't true?

推荐答案

我建议你先探测如果目标文件是否存在,如果是的,删除它。然后执行正常的移动操作。

I suggest you to probe first if the target file exists and if yes, delete it. Then execute a normal move operation.

由于这个顺序是不是原子,如果目标存在,你可能想,而不是将其重命名删除它,以避免失去它区分举失败。

Since this sequence is not atomic, in case the destination exists you might want to rename it instead of deleting it, to avoid losing it in case the move fails.

这篇关于模仿File.Move如果目标已经存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆