c#给原文件重命名

在 C# 里“原文件”指“物理文件”,用 System.IO 就够了——一行代码完成重命名:
csharp
复制
// 旧名字 → 新名字(同目录就是重命名,跨目录就是移动+改名)
System.IO.File.Move("old.txt", "new.txt");
 

完整模板(带判断、异常处理)

string oldPath = @"C:\Temp\old.txt"; string newPath = @"C:\Temp\new.txt";
if (!File.Exists(oldPath)) { Console.WriteLine("文件不存在"); return; }
try { // 同名文件已存在会被覆盖,加 overload 可禁止覆盖 File.Move(oldPath, newPath, overwrite: false); Console.WriteLine("重命名成功"); } catch (IOException ex) { Console.WriteLine($"失败:{ex.Message}"); }

UWP/WinUI 受限存储

如果文件在“用户不可见”的受保护目录(例如 UWP 的 ApplicationData),用 StorageFile
csharp
复制
var file = await StorageFile.GetFileFromPathAsync(oldPath);
await file.RenameAsync("new.txt", NameCollisionOption.FailIfExists);
 

.NET 6+ 一行极简

File.Move("old.txt", "new.txt", overwrite: true);

记住
  • File.Move 既能“重命名”也能“剪切”。
  • 同目录下只改文件名就是重命名;路径不同就是移动+改名。
posted @ 2025-09-15 16:52  yinghualeihenmei  阅读(328)  评论(0)    收藏  举报