c#怎么修改文件名

在 c# 中,可以通过使用 file.move() 方法来修改文件名。具体步骤如下:获取旧文件名获取文件所在的目录构造新文件名移动文件

c#怎么修改文件名

如何在 C# 中修改文件名

更改文件名的步骤:

  • 获取旧文件名:

    string oldFilename = "old-file.txt";
  • 获取文件所在的目录:

    string path = Path.GetDirectoryName(oldFilename);
  • 构造新文件名:

    string newFilename = "new-file.txt";
  • 移动文件,同时更改文件名:

    File.Move(Path.Combine(path, oldFilename), Path.Combine(path, newFilename));

示例:

以下代码示例演示了如何使用 File.Move() 方法更改文件名:

using System;
using System.IO;

namespace FileNameChanger
{
    class Program
    {
        static void Main(string[] args)
        {
            // 获取旧文件名
            string oldFileName = "old-file.txt";

            // 获取文件所在的目录
            string path = Path.GetDirectoryName(oldFileName);

            // 构造新文件名
            string newFileName = "new-file.txt";

            // 移动文件,同时更改文件名
            File.Move(Path.Combine(path, oldFileName), Path.Combine(path, newFileName));

            Console.WriteLine($"文件已重命名为 {newFileName}");
        }
    }
}

以上就是c#怎么修改文件名的详细内容,更多请关注www.sxiaw.com其它相关文章!