[C#] - Natively rename files or directories

Discussion in 'Mixed Languages' started by Josh Cell, Jan 16, 2012.

  1. Josh Cell

    Josh Cell MDL Developer

    Jan 8, 2011
    3,519
    7,108
    120
    #1 Josh Cell, Jan 16, 2012
    Last edited by a moderator: Apr 20, 2017
    We know, C# not have an native method to rename files or folders (only move), with large files, can dalay some time, this code will help you to only rename the file or folder:

    1ST: Add the Microsoft.VisualBasic.MyServices refference;

    For directories:

    Code:
           private static bool RenameDirectory(string DirPath, string NewName)
            {
                try
                {
                    FileSystemProxy FileSystem = new Microsoft.VisualBasic.Devices.Computer().FileSystem;
                    FileSystem.RenameDirectory(DirPath, NewName);
                    FileSystem = null;
                    return true;
                }
                catch { return false; }
            }
    For files:

    Code:
            private static bool RenameDirectory(string FilePath, string NewName)
            {
                try
                {
                    FileSystemProxy FileSystem = new Microsoft.VisualBasic.Devices.Computer().FileSystem;
                    FileSystem.RenameFile(FilePath, NewName);
                    FileSystem = null;
                    return true;
                }
                catch { return false; }
            }
    The code return false if have an issue.

    Is it, good look on coding for all :eek:
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...
  2. master131

    master131 MDL Novice

    Apr 12, 2011
    45
    22
    0
    #2 master131, Jan 24, 2012
    Last edited: Jan 24, 2012
    That's wrong, File.Move (in System.IO) can rename files and just to test that it was 'slow' I renamed a 4.37GB ISO file and it completed in 0ms so I'm not sure what you're talking about. File.Move really calls the MoveFile API and if you read on MSDN on the MoveFile function page and look at remarks, you will see this:
     
  3. Josh Cell

    Josh Cell MDL Developer

    Jan 8, 2011
    3,519
    7,108
    120
    Thanks for your info.

    Really, I haven't looked into this point of the function...

    But, the method posted by me can help anyone on other developments without the IO interaction ;)
     
    Stop hovering to collapse... Click to collapse... Hover to expand... Click to expand...