“Directory.Move”替代允许覆盖

时间:2016-05-27 16:51:20

标签: c#

我有一个包含多个子目录的目录。我知道存储在Subs中的所有文件名都是唯一的,它只是文件(照片)被分类。我需要允许用户重命名子文件夹,因此使用Directory.Move我可以毫无问题地执行此操作。

如果他们希望重命名并将其与另一个文件夹合并(丢弃一个类别并将照片移动到现有类别中),似乎Directory.Move无法处理覆盖/合并,我很难找到一个很好的选择。有一个像Directory.Move提供的One-liner一样简单的替代方案会很不错。

在我的情况下,我不能预见到允许此操作的情况(除非我的文件重命名代码失败 - 以及着名的最后一句话 - 它不应该)。

在没有barfing负载的情况下,不知道要提供什么Code,但这是我当前的Directory.Move。

try { Directory.Move(DirBase + "\\" + ItemTypeDel, DirBase + "\\" + tbTypeRename.Text); }
catch (Exception e)
{
AH(e.Message, false);
}

为了澄清,这一切都将在同一个逻辑分区上完成。

(它也发生在我身上,前端用户可能是一个berk并尝试将目录结构写入tbTypeRename.Text,所以我将不得不考虑......)

提前感谢您的支持。我是C#的新手但很喜欢它!

修改

        string Dir1 = DirBase + "\\" + ItemTypeDel; //Source DIR
        string Dir2 = DirBase + "\\" + tbTypeRename.Text; //Destination DIR

        try
        {
            var PhotoFiles = Directory.EnumerateFiles(Dir1, "*", SearchOption.AllDirectories); //All file names bunged in PhotoFiles

            foreach (string currentFile in PhotoFiles) //Scanning through all Filenames with Foreach
            {
                string fileName = currentFile.Substring(Dir1.Length + 1); //Not sure atm what the Length + 1 is about, some thing to look into.
                Directory.Move(currentFile, Path.Combine(Dir2, fileName)); //Concatenate Source DIR with File Name to get full Path and move
            }
            Directory.Delete(Dir1, false); //Finally, Delete empty Source DIR
        }
        catch (Exception e)
        {
            AH(e.Message, false); //Hope this never appears.
        }

好的,我基本上是在Directory.EnumerateFiles上的MSDN页面here上的第一个示例,我使用此代码进行的前几次尝试似乎正常工作。从技术上讲,我可能会对Directory.Delete bool使用'true',但无论如何都会被移动。我实际上需要删除Directory.Delete,因为它稍后完成,似乎搞砸了我的SQL删除CMD。

美好时光。

0 个答案:

没有答案