开发者

How to rename a file in C#

开发者 https://www.devze.com 2022-12-10 00:55 出处:网络
Consider: strPath= c:\\images\\gallery\\add.gif I need to rename this file from add.gif to thumb1.gid, and Ishouldwrite one command method, whatever the file name. We need to

Consider:

strPath= c:\images\gallery\add.gif

I need to rename this file from add.gif to thumb1.gid, and I should write one command method, whatever the file name. We need to replace that name with this like below.

string strfilename = **"thumb"**

****Result thum.gif**

strPath=开发者_运维技巧 c:\images\gallery\thum.gif **


You have several problems, looking up the value in the XML file, and renaming the file.

To look up the number corresponding to Gallery2 or whatever, I would recommend having a look at Stack Overflow question How to implement a simple XPath lookup which explains how to look up nodes/values in an XML file.

To rename a file in .NET, use something like this:

using System.IO;

FileInfo fi = new FileInfo("c:\\images\\gallery\\add.gif");
if (fi.Exists)
{
    fi.MoveTo("c:\\images\\gallery\\thumb3.gif");
}

Of course, you would use string variables instead of string literals for the paths.

That should give you enough information to piece it together and solve your particular lookup-rename problem.


I created a utility method to help encapsulate how to rename a file.

    public class FileUtilities
    {
        public static void RenameFile(string oldFilenameWithPathWithExtension, string newFilenameWithoutPathWithExtension)
        {
            try 
            {
                string directoryPath = Path.GetDirectoryName(oldFilenameWithPathWithExtension);
                if (directoryPath == null)
                {
                    throw new Exception($"Directory not found in given path value:{oldFilenameWithPathWithExtension}");
                }

                var newFilenameWithPath = Path.Combine(directoryPath, newFilenameWithoutPathWithExtension);
                FileInfo fileInfo = new FileInfo(oldFilenameWithPathWithExtension);
                fileInfo.MoveTo(newFilenameWithPath);
            }
            catch (Exception e)
            {
                //Boiler plate exception handling
                Console.WriteLine(e);
                throw;
            }
        }
    }

I omitted several other file system checks that could optionally be done, but as @JoelCoehoorn pointed out in a comment on this page, the File System is Volatile, so wrapping it in a try-catch may be all that is necessary.

With that class in your library, now you can simply call:

            var fullFilename = @"C:\images\gallery\add.gif";
            var newFilename = "Thumb.gif";
            FileHelper.RenameFile(fullFilename,newFilename);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号