Ejemplo n.º 1
0
        public static void Move(this DirectoryInfo srcDir, string destPath,
                                NameCollisionOption nameCollisionOption)
        {
            if (string.IsNullOrWhiteSpace(destPath))
            {
                throw new ArgumentNullException(nameof(destPath));
            }
            if (!srcDir.Exists)
            {
                throw new DirectoryNotFoundException("Source folder is not exist");
            }
            var item = FileSystemInfoEx.GetFileSystemInfo(destPath);

            if (item.Exists)
            {
                if (!string.Equals(srcDir.FullName, item.FullName, StringComparison.OrdinalIgnoreCase))
                {
                    switch (nameCollisionOption)
                    {
                    case NameCollisionOption.GenerateUniqueName:
                        srcDir.Move(item.GetParent().FullName,
                                    ProductNextName(item.Name), nameCollisionOption);
                        return;

                    case NameCollisionOption.ReplaceExisting:
                        item.Delete();
                        break;

                    case NameCollisionOption.FailIfExists:
                        var type = item is DirectoryInfo ? "srcDir" : "file";
                        throw new IOException($"A {type} exists in {destPath}");

                    default:
                        throw new ArgumentException("invalid option", nameof(nameCollisionOption));
                    }
                }
                else
                {
                    if (string.Equals(srcDir.FullName, item.FullName, StringComparison.Ordinal))
                    {
                        throw new IOException("Source and destination folders are same");
                    }
                    else
                    {
                        srcDir.Move(item.GetParent(), ProductNextName(srcDir.Name),
                                    NameCollisionOption.GenerateUniqueName);
                        srcDir.Move(destPath, nameCollisionOption);
                        return;
                    }
                }
            }

            try
            {
                srcDir.MoveTo(destPath);
            }
            catch (IOException)
            {
                srcDir.CopyTo(destPath, nameCollisionOption);
                srcDir.Delete();
            }
        }