Rename a file in C#

2018-12-31 19:50发布

How do I rename a file using C#?

标签: c# file rename
15条回答
看风景的人
2楼-- · 2018-12-31 20:15
System.IO.File.Move(oldNameFullPath, newNameFullPath);
查看更多
无色无味的生活
3楼-- · 2018-12-31 20:15

I couldn't find approach which suits me, so i propose my version. Of course need input, error handling.

public void Rename(string filePath, string newFileName)
{
    var newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName + Path.GetExtension(filePath));
    System.IO.File.Move(filePath, newFilePath);
}
查看更多
与风俱净
4楼-- · 2018-12-31 20:16

Use:

using System.IO;

string oldFilePath = @"C:\OldFile.txt"; // Full path of old file
string newFilePath = @"C:\NewFile.txt"; // Full path of new file

if (File.Exists(newFilePath))
{
    File.Delete(newFilePath);
}
File.Move(oldFilePath, newFilePath);
查看更多
初与友歌
5楼-- · 2018-12-31 20:16

In my case, i want the name of the renamed file to be unique, so i add a datetime stamp to the name. This way, the filename of the 'old' log is always unique:

   if (File.Exists(clogfile))
            {
                Int64 fileSizeInBytes = new FileInfo(clogfile).Length;
                if (fileSizeInBytes > 5000000)
                {
                    string path = Path.GetFullPath(clogfile);
                    string filename = Path.GetFileNameWithoutExtension(clogfile);
                    System.IO.File.Move(clogfile, Path.Combine(path, string.Format("{0}{1}.log", filename, DateTime.Now.ToString("yyyyMMdd_HHmmss"))));
                }
            }
查看更多
流年柔荑漫光年
6楼-- · 2018-12-31 20:18

NOTE: In this example code we open a directory and search for PDF files with open and closed parenthesis in the name of the file. You can check and replace any character in the name you like or just specify a whole new name using replace functions.

There are other ways to work from this code to do more elaborate renames but my main intention was to show how to use File.Move to do a batch rename. This worked against 335 PDF files in 180 directories when I ran it on my laptop. This is spur of the moment code and there are more elaborate ways to do it.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BatchRenamer
{
    class Program
    {
        static void Main(string[] args)
        {
            var dirnames = Directory.GetDirectories(@"C:\the full directory path of files to rename goes here");

            int i = 0;

            try
            {
                foreach (var dir in dirnames)
                {
                    var fnames = Directory.GetFiles(dir, "*.pdf").Select(Path.GetFileName);

                    DirectoryInfo d = new DirectoryInfo(dir);
                    FileInfo[] finfo = d.GetFiles("*.pdf");

                    foreach (var f in fnames)
                    {
                        i++;
                        Console.WriteLine("The number of the file being renamed is: {0}", i);

                        if (!File.Exists(Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", ""))))
                        {
                            File.Move(Path.Combine(dir, f), Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", "")));
                        }
                        else
                        {
                            Console.WriteLine("The file you are attempting to rename already exists! The file path is {0}.", dir);
                            foreach (FileInfo fi in finfo)
                            {
                                Console.WriteLine("The file modify date is: {0} ", File.GetLastWriteTime(dir));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
    }
}
查看更多
孤独寂梦人
7楼-- · 2018-12-31 20:19

Take a look at System.IO.File.Move, "move" the file to a new name.

System.IO.File.Move("oldfilename", "newfilename");
查看更多
登录 后发表回答