feedwall
feedwall

Reputation: 1574

Rename a file in C# (NET 2.0) without moving it or using DOS / Visual Basic commands

I have not found yet a file-rename-function in .NET for C#, so I'm a bit confused how I would rename a file. I use the command prompt with Process.Start, but this isn't really professional and a black DOS window is popping up each time. Yes, I know there is something in the Visual Basic namespace, but this is not my intention to add the "visual-basic.dll" to my project.

I found some examples which "move" the file to rename it. It is a quite painful method and a shoddy workaround for things. Such footwork I can program myself.

Every language has renaming commands, so I am stunned that C# hasn't or I haven't found out yet. What is the right command?

For large files and to rename on CD, this code works, but your project will be partly converted into Visual Basic (as I understand it, maybe it is not so):

//Add the Microsoft.VisualBasic.MyServices reference and namespace in a project;

//For directories:

 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;
     } //Just shut up the error generator of Visual Studio
 }

 //For files:

 private static bool RenameFile(string FilePath, string NewName)
 {
     try
     {
         FileSystemProxy FileSystem = new Microsoft.VisualBasic.Devices.Computer().FileSystem;
         FileSystem.RenameFile(FilePath, NewName);
         FileSystem = null;
         return true;
     }
     catch {
         return false;
     } //Just shut up the error generator of Visual Studio
 }

Upvotes: 0

Views: 4923

Answers (1)

Preet Sangha
Preet Sangha

Reputation: 65476

A rename is just a move and vice versa, see the MSDN : File.Move

In the OS the operations are the same for all intents an purposes. That's why in explorer a move on the same partition is near instantaneous - just adjusts the file name and logical location. To Rename a file in the same directory you Move it to a new File Name in the same directory.

using System;
using System.IO;

class Test 
{
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        string path2 = @"c:\temp2\MyTest.txt";
        try 
        {
            if (!File.Exists(path)) 
            {
                // This statement ensures that the file is created,
                // but the handle is not kept.
                using (FileStream fs = File.Create(path)) {}
            }

            // Ensure that the target does not exist.
            if (File.Exists(path2)) 
            File.Delete(path2);

            // Move the file.
            File.Move(path, path2);
            Console.WriteLine("{0} was moved/renamed to {1}.", path, path2);

            // See if the original exists now.
            if (File.Exists(path)) 
            {
                Console.WriteLine("The original file still exists, which is unexpected.");
            } 
            else 
            {
                Console.WriteLine("The original file no longer exists, which is expected.");
            }           

        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

Upvotes: 7

Related Questions