簡體   English   中英

如何在C#中重命名文件

[英]How to rename a file in C#

考慮:

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

我需要將此文件從add.gif重命名為thumb1.gid ,並且我應該編寫一個命令方法,無論文件名如何。 我們需要用下面的名稱替換該名稱。

string strfilename = **"thumb"**

****結果thum.gif**

strPath= c:\\images\\gallery\\thum.gif **

您有幾個問題,在 XML 文件中查找值並重命名文件。

要查找與 Gallery2 或其他內容相對應的數字,我建議您查看 Stack Overflow 問題如何實現簡單的 XPath 查找,該問題解釋了如何在 XML 文件中查找節點/值。

要在 .NET 中重命名文件,請使用以下內容:

using System.IO;

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

當然,您將使用字符串變量而不是路徑的字符串文字。

這應該為您提供足夠的信息來將它們拼湊在一起並解決您的特定查找重命名問題。

我創建了一個實用方法來幫助封裝如何重命名文件。

    public class FileHelper 
    {
        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;
            }
        }
    }

我省略了其他幾個可以選擇完成的文件系統檢查,但正如@JoelCoehoorn 在本頁的評論中指出的那樣,文件系統是易失性的,因此可能只需要將其包裝在 try-catch 中即可。

有了圖書館里的那個類,現在你可以簡單地調用:

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

暫無
暫無

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

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