Move() public static method

public static Move ( string sourceDirName, string destDirName ) : void
sourceDirName string
destDirName string
return void
 /// <summary>
 /// Перемещает весь каталог со всем его содержимым в новый каталог либо только файлы из текущего каталога.
 /// </summary>
 /// <param name="NewName">Путь, куда нужно переместить.</param>
 /// <param name="onlyFiles">При значении true — перемещает только файлы текущего каталога.</param>
 public void moveto(string NewName, bool onlyFiles)
 {
     if (!SDirectory.Exists(dname) & dname.Length <= 260 & NewName.Length <= 260)//проверка на существование директории, корректности имени перемещаемой папки и принимающей перемещение
     {
         try
         {
             if (!onlyFiles)
             {
                 SDirectory.Move(dname, NewName); //создание директории
                 dname = NewName;                 //переопределение рабочей папки
             }
             else
             {
                 DirectoryInfo _d = new DirectoryInfo(dname);
                 foreach (string f in SDirectory.GetFiles(dname))
                 {
                     SFile.Move(f, NewName);
                 }
             }
         }
         catch (Exception e)                                   //обработка исключений для перемещения
         {
             LogForOperations("Перемещение папки", e.Message); //запись ошибки (если есть) в лог
             throw e;
         }
     }
     else
     {
         LogForOperations("Перемещение папки", "операция с папкой невозможна, т.к. перемещаемая папка не существует либо в имени больше 260 символов, либо папка с новым именем уже существует");//запись ошибки в лог, если не выполнилась проверка
     }
 }
        public void CanSyncExtA_MoveTest()
        {
            var externalDrivePath = Path.Combine(Path.GetTempPath(), "CryptoDriveExternal_" + Guid.NewGuid().ToString());
            var externalDrive     = new LocalDriveProxy(externalDrivePath, "External", _logger);

            this.Execute("", async() =>
            {
                await externalDrive.CreateOrUpdateAsync(Utils.DriveItemPool["/sub/a1"]);

                /* move folder from external drive to local drive */
                _logger.LogInformation("TEST: Move folder from external drive to local drive.");
                var newDriveItem = Utils.DriveItemPool["/sub/a1"].MemberwiseClone();
                var sourcePath   = Path.GetDirectoryName(newDriveItem.GetAbsolutePath(externalDrivePath));
                var targetPath   = Path.GetDirectoryName(newDriveItem.GetAbsolutePath(_driveHive.LocalDrivePath));

                Directory.Move(sourcePath, targetPath);
            },
                         () =>
            {
                Assert.True(Directory.Exists("/sub".ToAbsolutePath(_driveHive.RemoteDrivePath)), "Folder does not exist.");
                Assert.True(File.Exists("/sub/a".ToAbsolutePath(_driveHive.RemoteDrivePath)), "File does not exist.");
            }, syncId: 1);

            Directory.Delete(externalDrivePath, true);
        }
        public void HandleBookRename_CaseChangeOnly_WorksRight()
        {
            // Setup //
            const string originalBookName = "A new book";
            var          bookBuilder      = new BookFolderBuilder()
                                            .WithRootFolder(_collectionFolder.FolderPath)
                                            .WithTitle(originalBookName)
                                            .WithHtm("<html><body>This is just a dummy</body></html>")
                                            .Build();
            string bookFolderPath = bookBuilder.BuiltBookFolderPath;
            string htmlPath       = bookBuilder.BuiltBookHtmPath;

            TeamCollectionManager.ForceCurrentUserForTests("*****@*****.**");
            _collection.PutBook(bookFolderPath);

            var locked = _collection.AttemptLock(originalBookName);

            Assert.That(locked, Is.True, "successfully checked out book to [email protected]");

            // SUT: rename changes status in local collection folder, but not in shared repo folder
            const string newBookName       = "A New Book";
            var          newBookFolderPath = Path.Combine(_collectionFolder.FolderPath, newBookName);

            File.Move(htmlPath, Path.Combine(bookFolderPath, newBookName + ".htm"));
            // renaming directory doesn't work when names are 'the same'
            var tempPath = Path.Combine(_collectionFolder.FolderPath, "tempxxyy");

            Directory.Move(bookFolderPath, tempPath);
            Directory.Move(tempPath, newBookFolderPath);

            _collection.HandleBookRename(originalBookName, newBookName);

            _collection.PutBook(newBookFolderPath, true);

            var newRepoPath = Path.Combine(_sharedFolder.FolderPath, "Books", newBookName + ".bloom");

            // It should not have been deleted! This is a regression test for BL-10156.
            // The danger is that Windows considers the old and new names the same, so after
            // we move the file to the new name, if we go to delete the old name, we get rid of the new one.
            Assert.That(File.Exists(newRepoPath));

            // Did it get renamed?
            var matchingFiles = Directory.EnumerateFiles(Path.Combine(_sharedFolder.FolderPath, "Books"), newBookName + ".bloom").ToArray();

            Assert.That(matchingFiles[0], Is.EqualTo(Path.Combine(_sharedFolder.FolderPath, "Books", newBookName + ".bloom")));

            var newStatus  = _collection.GetLocalStatus(newBookName);
            var repoStatus = _collection.GetStatus(newBookName);

            Assert.That(newStatus, Is.Not.Null, "local status of renamed book is not null");
            Assert.That(repoStatus, Is.Not.Null, "repo status of renamed book is not null");
            Assert.That(newStatus.checksum, Is.EqualTo(repoStatus.checksum), "checksums of local and remote match after rename");
            Assert.That(newStatus.lockedBy, Is.EqualTo(null), "lockedBy of local and remote match after rename");
            Assert.That(newStatus.oldName, Is.Null, "local status has original name cleared after commit");
        }
Beispiel #4
0
    /// <summary>
    ///     Moves a directory to another location.
    /// </summary>
    /// <param name="sourceDirName">The source directory name.</param>
    /// <param name="destDirName">The destination directory name.</param>
    /// <exception cref="ArgumentNullException">
    ///     <paramref name="destDirName" /> or <paramref name="sourceDirName" /> is <see langword="null" /> (
    ///     <see langword="Nothing" /> in Visual Basic).
    /// </exception>
    public void Move(
        string sourceDirName,
        string destDirName)
    {
        _ = Requires.NotNullOrWhiteSpace(
            sourceDirName,
            nameof(sourceDirName));
        _ = Requires.NotNullOrWhiteSpace(
            destDirName,
            nameof(destDirName));

        FSDir.Move(
            sourceDirName,
            destDirName);
    }
Beispiel #5
0
    /// <summary>
    ///     Asynchronously moves a directory to another location.
    /// </summary>
    /// <param name="sourceDirectoryName">The source directory name.</param>
    /// <param name="destinationDirectoryName">The destination directory name.</param>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <returns>A task.</returns>
    public Task MoveAsync(
        string sourceDirectoryName,
        string destinationDirectoryName,
        CancellationToken cancellationToken = default)
    {
        _ = Requires.NotNullOrWhiteSpace(
            sourceDirectoryName,
            nameof(sourceDirectoryName));
        _ = Requires.NotNullOrWhiteSpace(
            destinationDirectoryName,
            nameof(destinationDirectoryName));

        return(Work.OnThreadPoolAsync(
                   state => FSDir.Move(
                       state.Source,
                       state.Destination),
                   (Source: sourceDirectoryName, Destination: destinationDirectoryName),
                   cancellationToken));
    }
 /// <summary>
 /// Переименование каталога.
 /// </summary>
 /// <param name="NewName">Новое имя.</param>
 public void rename(string NewName)
 {
     try
     {
         if (SDirectory.Exists(dname) & dname.Length <= 260 & !SDirectory.Exists(NewName) & NewName.Length <= 260) //проверка на корректность имен каталогов, существование переименуемой дироектории и несуществовании директории с таким именем
         {
             SDirectory.Move(dname, NewName);                                                                      //переименование директории
             dname = NewName;                                                                                      //переопределение рабочей директории
         }
         else
         {
             LogForOperations("Переименование папки", "операция с папкой невозможна, т.к. папка не существует либо в имени больше 260 символов, либо папка с новым именем уже существует");//запись в лог ошибки, если не выполнились условия проверки
         }
     }
     catch (Exception e)                                      //обработка исключений для переименования
     {
         LogForOperations("Переименование папки", e.Message); //запись в лог ошибки (если есть)
         throw e;
     }
 }
        public void HandleBookRename_CheckedOutToMe_FixesStatusProperly()
        {
            // Setup //
            const string originalBookName = "Hello. Goodbye!";
            var          bookBuilder      = new BookFolderBuilder()
                                            .WithRootFolder(_collectionFolder.FolderPath)
                                            .WithTitle(originalBookName)
                                            .WithHtm("<html><body>This is just a dummy</body></html>")
                                            .Build();
            string bookFolderPath = bookBuilder.BuiltBookFolderPath;
            string htmlPath       = bookBuilder.BuiltBookHtmPath;

            TeamCollectionManager.ForceCurrentUserForTests("*****@*****.**");
            _collection.PutBook(bookFolderPath);

            var locked = _collection.AttemptLock(originalBookName);

            Assert.That(locked, Is.True, "successfully checked out book to [email protected]");

            // SUT: rename changes status in local collection folder, but not in shared repo folder
            const string newBookName       = "Testing is Fun. Sometimes";
            var          newBookFolderPath = Path.Combine(_collectionFolder.FolderPath, newBookName);

            File.Move(htmlPath, Path.Combine(bookFolderPath, newBookName + ".htm"));
            Directory.Move(bookFolderPath, newBookFolderPath);

            _collection.HandleBookRename(originalBookName, newBookName);
            var newStatus  = _collection.GetLocalStatus(newBookName);
            var repoStatus = _collection.GetStatus(newBookName);

            Assert.That(newStatus, Is.Not.Null, "local status of renamed book is not null");
            Assert.That(repoStatus, Is.Not.Null, "repo status of renamed book is not null");
            Assert.That(newStatus.checksum, Is.EqualTo(repoStatus.checksum), "checksums of local and remote match after rename");
            Assert.That(newStatus.lockedBy, Is.EqualTo(repoStatus.lockedBy), "lockedBy of local and remote match after rename");
            Assert.That(newStatus.lockedWhen, Is.EqualTo(repoStatus.lockedWhen), "lockedWhen of local and remote match after rename");
            Assert.That(newStatus.lockedWhere, Is.EqualTo(repoStatus.lockedWhere), "lockedWhere of local and remote match after rename");
            Assert.That(newStatus.oldName, Is.EqualTo(originalBookName), "local status has original name in oldName field after rename");
            Assert.That(repoStatus.oldName, Is.Null, "repo status still has null oldName field after rename");
        }
Beispiel #8
0
        public Task <DriveItem> MoveAsync(DriveItem oldDriveItem, DriveItem newDriveItem)
        {
            var fullOldPath = oldDriveItem.GetAbsolutePath(this.BasePath);
            var fullNewPath = newDriveItem.GetAbsolutePath(this.BasePath);

            switch (newDriveItem.Type())
            {
            case DriveItemType.Folder:
                Directory.Move(fullOldPath, fullNewPath);
                break;

            case DriveItemType.File:
                Directory.CreateDirectory(Path.GetDirectoryName(fullNewPath));
                File.Move(fullOldPath, fullNewPath);
                break;

            case DriveItemType.RemoteItem:
            default:
                throw new NotSupportedException();
            }

            return(Task.FromResult(newDriveItem));
        }
Beispiel #9
0
        public void UpdateDirectoryName(string directoryPath, DirectoryScanResult scanResult)
        {
            var directoryName = new DirectoryInfo(directoryPath).Name;

            if (scanResult.StartingDate.HasValue && scanResult.EndingDate.HasValue)
            {
                // start and end dates are set
                if (scanResult.StartingDate.Value.Year != scanResult.EndingDate.Value.Year)
                {
                    Console.WriteLine("Detected a directory that has pictures taken in different years, skipping.");
                    return;
                }

                string suggestedDirectoryName;
                if (scanResult.StartingDate.Value.Month != scanResult.EndingDate.Value.Month)
                {
                    suggestedDirectoryName =
                        $"{scanResult.StartingDate.Value.ToString("yyyy-MM-dd")}-{scanResult.EndingDate.Value.ToString("yyyy-MM-dd")} {directoryName}";
                }
                else if (scanResult.StartingDate.Value.Day != scanResult.EndingDate.Value.Day)
                {
                    suggestedDirectoryName =
                        $"{scanResult.StartingDate.Value.ToString("yyyy-MM-dd")}-{scanResult.EndingDate.Value.ToString("yyyy-MM-dd")} {directoryName}";
                }
                else
                {
                    suggestedDirectoryName = $"{scanResult.StartingDate.Value.ToString("yyyy-MM-dd")} {directoryName}";
                }

                Console.WriteLine($"Changing {directoryName} -> {suggestedDirectoryName}");
                Directory.Move(directoryPath, directoryPath.Replace(directoryName, suggestedDirectoryName));
            }
            else
            {
                Console.WriteLine($"Directory {directoryName} did not return any scan result, no need to change its name.");
            }
        }
Beispiel #10
0
 public static void Move(string sourceDirName, string destDirName) =>
 MSIOD.Move(sourceDirName, destDirName);
 public static void Move(string f, string t) => OgDir.Move(f, t);
Beispiel #12
0
        private void _dragDropManager_DragDrop(object sender, FilesDragEventArgs e)
        {
            EndDragDrop();

            var node = _treeView.GetNodeAt(_treeView.PointToClient(new Point(e.X, e.Y)));

            if (node == null)
            {
                return;
            }

            string targetPath = (string)node.Tag;

            var matches = BuildMatches(targetPath, e);

            if (matches == null)
            {
                return;
            }

            try
            {
                foreach (var match in matches)
                {
                    string target = Path.Combine(targetPath, Path.GetFileName(match.Path));

                    if (match.Kind.IsFile() && File.Exists(target))
                    {
                        var result = TaskDialogEx.Show(
                            this,
                            "The destination already has a file with this name. Do you want to overwrite the existing file?",
                            FindForm().Text,
                            TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel,
                            TaskDialogIcon.Warning
                            );

                        if (result == DialogResult.No)
                        {
                            continue;
                        }
                        if (result == DialogResult.Cancel)
                        {
                            return;
                        }

                        File.Delete(target);
                    }

                    switch (match.Kind)
                    {
                    case DropMatchKind.DirectoryMove:
                        IODirectory.Move(match.Path, target);
                        break;

                    case DropMatchKind.DirectoryCopy:
                        PathUtil.CopyDirectory(match.Path, target);
                        break;

                    case DropMatchKind.FileMove:
                        File.Move(match.Path, target);
                        break;

                    case DropMatchKind.FileCopy:
                        File.Copy(match.Path, target);
                        break;

                    case DropMatchKind.FileVirtual:
                        File.WriteAllBytes(target, e.DropData.GetFileData(match.Index));
                        break;
                    }
                }
            }
            catch
            {
                TaskDialogEx.Show(this, "Could not complete the operation", FindForm().Text, TaskDialogCommonButtons.OK, TaskDialogIcon.Error);
            }
        }
 /// <summary>
 /// Asynchronous extension for <see cref="Directory.Move" /> method.
 /// </summary>
 /// <param name="sourceDirName">Same with <see cref="Directory.Move" /> sourceDirName.</param>
 /// <param name="destDirName">Same with <see cref="Directory.Move" /> destDirName.</param>
 /// <param name="cancellationToken">A <see cref="CancellationToken" /> that should be used to cancel the work.</param>
 /// <returns>A <see cref="Task"/> that represents the work queued to execute in the ThreadPool.</returns>
 public static async Task MoveAsync(string sourceDirName, string destDirName, CancellationToken cancellationToken = default(CancellationToken))
 {
     await Task.Run(() => Directory.Move(sourceDirName, destDirName), cancellationToken);
 }