簡體   English   中英

重命名文件 C#

[英]Rename a file in C#

如何使用 C# 重命名文件?

看看System.IO.File.Move ,將文件“移動”到一個新名稱。

System.IO.File.Move("oldfilename", "newfilename");
System.IO.File.Move(oldNameFullPath, newNameFullPath);

在 File.Move 方法中,如果文件已經存在,這不會覆蓋文件。 並且會拋出異常。

所以我們需要檢查文件是否存在。

/* Delete the file if exists, else no exception thrown. */

File.Delete(newFileName); // Delete the existing file if exists
File.Move(oldFileName,newFileName); // Rename the oldFileName into newFileName

或者用 try catch 包圍它以避免異常。

只需添加:

namespace System.IO
{
    public static class FileInfoExtensions
    {
        public static void Rename(this FileInfo fileInfo, string newName)
        {
            fileInfo.MoveTo(Path.Combine(fileInfo.Directory.FullName, newName));
        }
    }
}

接着...

FileInfo file = new FileInfo("c:\test.txt");
file.Rename("test2.txt");

您可以使用File.Move來做到這一點。

  1. 第一個解決方案

    避免在此處發布System.IO.File.Move解決方案(包括標記的答案)。 它在網絡上發生故障。 但是,復制/刪除模式在本地和網絡上都有效。 遵循其中一種移動解決方案,但將其替換為 Copy。 然后使用 File.Delete 刪除原始文件。

    您可以創建一個重命名方法來簡化它。

  2. 便於使用

    在 C# 中使用 VB 程序集。 添加對 Microsoft.VisualBasic 的引用

    然后重命名文件:

    Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(myfile, newName);

    兩者都是字符串。 請注意, myfile 具有完整路徑。 newName 沒有。 例如:

     a = "C:\\whatever\\a.txt"; b = "b.txt"; Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(a, b);

    C:\\whatever\\文件夾現在將包含b.txt

您可以將其復制為一個新文件,然后使用System.IO.File類刪除舊文件:

if (File.Exists(oldName))
{
    File.Copy(oldName, newName, true);
    File.Delete(oldName);
}

注意:在此示例代碼中,我們打開一個目錄並搜索文件名中帶有左括號和右括號的 PDF 文件。 您可以檢查並替換您喜歡的名稱中的任何字符,或者使用替換功能指定一個全新的名稱。

還有其他方法可以從這段代碼中進行更精細的重命名,但我的主要目的是展示如何使用 File.Move 進行批量重命名。 當我在筆記本電腦上運行它時,這對 180 個目錄中的 335 個 PDF 文件有效。 這是一時興起的代碼,有更精細的方法可以做到。

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();
        }
    }
}

利用:

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);

利用:

public static class FileInfoExtensions
{
    /// <summary>
    /// Behavior when a new filename exists.
    /// </summary>
    public enum FileExistBehavior
    {
        /// <summary>
        /// None: throw IOException "The destination file already exists."
        /// </summary>
        None = 0,
        /// <summary>
        /// Replace: replace the file in the destination.
        /// </summary>
        Replace = 1,
        /// <summary>
        /// Skip: skip this file.
        /// </summary>
        Skip = 2,
        /// <summary>
        /// Rename: rename the file (like a window behavior)
        /// </summary>
        Rename = 3
    }


    /// <summary>
    /// Rename the file.
    /// </summary>
    /// <param name="fileInfo">the target file.</param>
    /// <param name="newFileName">new filename with extension.</param>
    /// <param name="fileExistBehavior">behavior when new filename is exist.</param>
    public static void Rename(this System.IO.FileInfo fileInfo, string newFileName, FileExistBehavior fileExistBehavior = FileExistBehavior.None)
    {
        string newFileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(newFileName);
        string newFileNameExtension = System.IO.Path.GetExtension(newFileName);
        string newFilePath = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileName);

        if (System.IO.File.Exists(newFilePath))
        {
            switch (fileExistBehavior)
            {
                case FileExistBehavior.None:
                    throw new System.IO.IOException("The destination file already exists.");

                case FileExistBehavior.Replace:
                    System.IO.File.Delete(newFilePath);
                    break;

                case FileExistBehavior.Rename:
                    int dupplicate_count = 0;
                    string newFileNameWithDupplicateIndex;
                    string newFilePathWithDupplicateIndex;
                    do
                    {
                        dupplicate_count++;
                        newFileNameWithDupplicateIndex = newFileNameWithoutExtension + " (" + dupplicate_count + ")" + newFileNameExtension;
                        newFilePathWithDupplicateIndex = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileNameWithDupplicateIndex);
                    }
                    while (System.IO.File.Exists(newFilePathWithDupplicateIndex));

                    newFilePath = newFilePathWithDupplicateIndex;
                    break;

                case FileExistBehavior.Skip:
                    return;
            }
        }
        System.IO.File.Move(fileInfo.FullName, newFilePath);
    }
}

如何使用此代碼

class Program
{
    static void Main(string[] args)
    {
        string targetFile = System.IO.Path.Combine(@"D://test", "New Text Document.txt");
        string newFileName = "Foo.txt";

        // Full pattern
        System.IO.FileInfo fileInfo = new System.IO.FileInfo(targetFile);
        fileInfo.Rename(newFileName);

        // Or short form
        new System.IO.FileInfo(targetFile).Rename(newFileName);
    }
}

沒有一個答案提到編寫一個單元可測試的解決方案。 您可以使用System.IO.Abstractions因為它提供了一個圍繞 FileSystem 操作的可測試包裝器,您可以使用它創建模擬文件系統對象並編寫單元測試。

using System.IO.Abstractions;

IFileInfo fileInfo = _fileSystem.FileInfo.FromFileName("filePathAndName");
fileInfo.MoveTo(Path.Combine(fileInfo.DirectoryName, newName));

它已經過測試,並且是重命名文件的工作代碼。

我找不到適合我的方法,所以我提出了我的版本。 當然,它需要輸入和錯誤處理。

public void Rename(string filePath, string newFileName)
{
    var newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName + Path.GetExtension(filePath));
    System.IO.File.Move(filePath, newFilePath);
}

就我而言,我希望重命名文件的名稱是唯一的,因此我在名稱中添加了日期時間戳。 這樣,“舊”日志的文件名始終是唯一的:

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"))));
    }
}

移動正在做同樣的事情 =復制刪除舊的。

File.Move(@"C:\ScanPDF\Test.pdf", @"C:\BackupPDF\" + string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.pdf", DateTime.Now));
public static class ImageRename
{
    public static void ApplyChanges(string fileUrl,
                                    string temporaryImageName,
                                    string permanentImageName)
    {
        var currentFileName = Path.Combine(fileUrl,
                                           temporaryImageName);

        if (!File.Exists(currentFileName))
            throw new FileNotFoundException();

        var extention = Path.GetExtension(temporaryImageName);
        var newFileName = Path.Combine(fileUrl,
                                       $"{permanentImageName}
                                         {extention}");

        if (File.Exists(newFileName))
            File.Delete(newFileName);

        File.Move(currentFileName, newFileName);
    }
}

我遇到過一個案例,當我不得不在事件處理程序中重命名文件時,它會觸發任何文件更改,包括重命名,並永遠跳過我必須重命名的文件的重命名,使用:

  1. 制作副本
  2. 移除原件
File.Copy(fileFullPath, destFileName); // Both have the format of "D:\..\..\myFile.ext"
Thread.Sleep(100); // Wait for the OS to unfocus the file
File.Delete(fileFullPath);
private static void Rename_File(string FileFullPath, string NewName) // nes name without directory actualy you can simply rename with fileinfo.MoveTo(Fullpathwithnameandextension);
        {
            FileInfo fileInfo = new FileInfo(FileFullPath);
            string DirectoryRoot = Directory.GetParent(FileFullPath).FullName;

            string filecreator = FileFullPath.Substring(DirectoryRoot.Length,FileFullPath.Length-DirectoryRoot.Length);
             
            filecreator = DirectoryRoot + NewName;
            try
            {
                fileInfo.MoveTo(filecreator);
            }
            catch(Exception ex)
            {
                Console.WriteLine(filecreator);
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }

    enter code here
            // string FileDirectory = Directory.GetDirectoryRoot()

        }
// Source file to be renamed  
string sourceFile = @"C:\Temp\MaheshChand.jpg";  
// Create a FileInfo  
System.IO.FileInfo fi = new System.IO.FileInfo(sourceFile);  
// Check if file is there  
if (fi.Exists)  
{  
// Move file with a new name. Hence renamed.  
fi.MoveTo(@"C:\Temp\Mahesh.jpg");  
Console.WriteLine("File Renamed.");  
}  
public void RenameFile(string filePath, string newName)
{
    FileInfo fileInfo = new FileInfo(filePath);
    fileInfo.MoveTo(fileInfo.Directory.FullName + "\\" + newName);
}

利用:

int rename(const char * oldname, const char * newname);

rename() 函數在stdio.h頭文件中定義。 它將文件或目錄從oldname重命名為newname 重命名操作與移動相同,因此您也可以使用此功能移動文件。

當 C# 沒有某些功能時,我使用 C++ 或 C:

public partial class Program
{
    [DllImport("msvcrt", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
    public static extern int rename(
            [MarshalAs(UnmanagedType.LPStr)]
            string oldpath,
            [MarshalAs(UnmanagedType.LPStr)]
            string newpath);

    static void FileRename()
    {
        while (true)
        {
            Console.Clear();
            Console.Write("Enter a folder name: ");
            string dir = Console.ReadLine().Trim('\\') + "\\";
            if (string.IsNullOrWhiteSpace(dir))
                break;
            if (!Directory.Exists(dir))
            {
                Console.WriteLine("{0} does not exist", dir);
                continue;
            }
            string[] files = Directory.GetFiles(dir, "*.mp3");

            for (int i = 0; i < files.Length; i++)
            {
                string oldName = Path.GetFileName(files[i]);
                int pos = oldName.IndexOfAny(new char[] { '0', '1', '2' });
                if (pos == 0)
                    continue;

                string newName = oldName.Substring(pos);
                int res = rename(files[i], dir + newName);
            }
        }
        Console.WriteLine("\n\t\tPress any key to go to main menu\n");
        Console.ReadKey(true);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM