我如何重命名一个文件使用c# ?
当前回答
你可以将它复制为一个新文件,然后使用System.IO.File类删除旧文件:
if (File.Exists(oldName))
{
File.Copy(oldName, newName, true);
File.Delete(oldName);
}
其他回答
注意:在这个示例代码中,我们打开一个目录并搜索PDF文件,文件名中包含开括号和闭括号。您可以检查和替换名称中的任何字符,或者使用替换函数指定一个全新的名称。
从这段代码中还可以使用其他方法来进行更详细的重命名,但我的主要目的是展示如何使用File。移动做批量重命名。当我在我的笔记本电脑上运行它时,它可以处理180个目录中的335个PDF文件。这是一时兴起的代码,还有更详细的方法来实现它。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BatchRenamer
{
class Program
{
static void Main(string[] args)
{
var dirnames = Directory.GetDirectories(@"C:\the full directory path of files to rename goes here");
int i = 0;
try
{
foreach (var dir in dirnames)
{
var fnames = Directory.GetFiles(dir, "*.pdf").Select(Path.GetFileName);
DirectoryInfo d = new DirectoryInfo(dir);
FileInfo[] finfo = d.GetFiles("*.pdf");
foreach (var f in fnames)
{
i++;
Console.WriteLine("The number of the file being renamed is: {0}", i);
if (!File.Exists(Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", ""))))
{
File.Move(Path.Combine(dir, f), Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", "")));
}
else
{
Console.WriteLine("The file you are attempting to rename already exists! The file path is {0}.", dir);
foreach (FileInfo fi in finfo)
{
Console.WriteLine("The file modify date is: {0} ", File.GetLastWriteTime(dir));
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.Read();
}
}
}
private static void Rename_File(string FileFullPath, string NewName) // nes name without directory actualy you can simply rename with fileinfo.MoveTo(Fullpathwithnameandextension);
{
FileInfo fileInfo = new FileInfo(FileFullPath);
string DirectoryRoot = Directory.GetParent(FileFullPath).FullName;
string filecreator = FileFullPath.Substring(DirectoryRoot.Length,FileFullPath.Length-DirectoryRoot.Length);
filecreator = DirectoryRoot + NewName;
try
{
fileInfo.MoveTo(filecreator);
}
catch(Exception ex)
{
Console.WriteLine(filecreator);
Console.WriteLine(ex.Message);
Console.ReadKey();
}
enter code here
// string FileDirectory = Directory.GetDirectoryRoot()
}
Use:
public static class FileInfoExtensions
{
/// <summary>
/// Behavior when a new filename exists.
/// </summary>
public enum FileExistBehavior
{
/// <summary>
/// None: throw IOException "The destination file already exists."
/// </summary>
None = 0,
/// <summary>
/// Replace: replace the file in the destination.
/// </summary>
Replace = 1,
/// <summary>
/// Skip: skip this file.
/// </summary>
Skip = 2,
/// <summary>
/// Rename: rename the file (like a window behavior)
/// </summary>
Rename = 3
}
/// <summary>
/// Rename the file.
/// </summary>
/// <param name="fileInfo">the target file.</param>
/// <param name="newFileName">new filename with extension.</param>
/// <param name="fileExistBehavior">behavior when new filename is exist.</param>
public static void Rename(this System.IO.FileInfo fileInfo, string newFileName, FileExistBehavior fileExistBehavior = FileExistBehavior.None)
{
string newFileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(newFileName);
string newFileNameExtension = System.IO.Path.GetExtension(newFileName);
string newFilePath = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileName);
if (System.IO.File.Exists(newFilePath))
{
switch (fileExistBehavior)
{
case FileExistBehavior.None:
throw new System.IO.IOException("The destination file already exists.");
case FileExistBehavior.Replace:
System.IO.File.Delete(newFilePath);
break;
case FileExistBehavior.Rename:
int dupplicate_count = 0;
string newFileNameWithDupplicateIndex;
string newFilePathWithDupplicateIndex;
do
{
dupplicate_count++;
newFileNameWithDupplicateIndex = newFileNameWithoutExtension + " (" + dupplicate_count + ")" + newFileNameExtension;
newFilePathWithDupplicateIndex = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileNameWithDupplicateIndex);
}
while (System.IO.File.Exists(newFilePathWithDupplicateIndex));
newFilePath = newFilePathWithDupplicateIndex;
break;
case FileExistBehavior.Skip:
return;
}
}
System.IO.File.Move(fileInfo.FullName, newFilePath);
}
}
如何使用此代码
class Program
{
static void Main(string[] args)
{
string targetFile = System.IO.Path.Combine(@"D://test", "New Text Document.txt");
string newFileName = "Foo.txt";
// Full pattern
System.IO.FileInfo fileInfo = new System.IO.FileInfo(targetFile);
fileInfo.Rename(newFileName);
// Or short form
new System.IO.FileInfo(targetFile).Rename(newFileName);
}
}
我找不到适合我的方法,所以我提出了我的版本。当然,它需要输入和错误处理。
public void Rename(string filePath, string newFileName)
{
var newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName + Path.GetExtension(filePath));
System.IO.File.Move(filePath, newFilePath);
}
// Source file to be renamed
string sourceFile = @"C:\Temp\MaheshChand.jpg";
// Create a FileInfo
System.IO.FileInfo fi = new System.IO.FileInfo(sourceFile);
// Check if file is there
if (fi.Exists)
{
// Move file with a new name. Hence renamed.
fi.MoveTo(@"C:\Temp\Mahesh.jpg");
Console.WriteLine("File Renamed.");
}