如何在 C# 中修改文件名
更改文件名的步骤:
获取旧文件名:
<code class="csharp">string oldFilename = "old-file.txt";</code>
获取文件所在的目录:
<code class="csharp">string path = Path.GetDirectoryName(oldFilename);</code>
构造新文件名:
<code class="csharp">string newFilename = "new-file.txt";</code>
移动文件,同时更改文件名:
<code class="csharp">File.Move(Path.Combine(path, oldFilename), Path.Combine(path, newFilename));</code>
示例:
以下代码示例演示了如何使用
File.Move()方法更改文件名:
<code class="csharp">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}");
}
}
}</code> 