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


当前回答

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

其他回答

System.IO.File.Move(oldNameFullPath, newNameFullPath);

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.

public void RenameFile(string filePath, string newName)
{
    FileInfo fileInfo = new FileInfo(filePath);
    fileInfo.MoveTo(fileInfo.Directory.FullName + "\\" + newName);
}

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

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

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