我如何重命名一个文件使用c# ?


当前回答

我遇到过一种情况,当我不得不在事件处理程序中重命名文件时,它会触发任何文件更改,包括重命名,并且要跳过永远重命名我必须重命名的文件,使用:

创建副本 移除原始的

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

其他回答

看一下System.IO.File。移动,“移动”文件到一个新名称。

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

添加:

namespace System.IO
{
    public static class ExtendedMethod
    {
        public static void Rename(this FileInfo fileInfo, string newName)
        {
            fileInfo.MoveTo(fileInfo.Directory.FullName + "\\" + newName);
        }
    }
}

然后……

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

Move是做同样的=复制和删除旧的。

File.Move(@"C:\ScanPDF\Test.pdf", @"C:\BackupPDF\" + string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.pdf", DateTime.Now));

First solution Avoid System.IO.File.Move solutions posted here (marked answer included). It fails over networks. However, copy/delete pattern works locally and over networks. Follow one of the move solutions, but replace it with Copy instead. Then use File.Delete to delete the original file. You can create a Rename method to simplify it. Ease of use Use the VB assembly in C#. Add reference to Microsoft.VisualBasic Then to rename the file: Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(myfile, newName); Both are strings. Note that myfile has the full path. newName does not. For example: a = "C:\whatever\a.txt"; b = "b.txt"; Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(a, b); The C:\whatever\ folder will now contain b.txt.

Use:

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