Chr*_*lor 903
看看System.IO.File.Move,将文件"移动"到一个新名称.
System.IO.File.Move("oldfilename", "newfilename");
Run Code Online (Sandbox Code Playgroud)
Ale*_*tic 124
System.IO.File.Move(oldNameFullPath, newNameFullPath);
Run Code Online (Sandbox Code Playgroud)
Moh*_*han 42
在File.Move方法中,如果文件已存在,则不会覆盖该文件.它会引发异常.
所以我们需要检查文件是否存在.
/* Delete the file if exists, else no exception thrown. */
File.Delete(newFileName); // Delete the existing file if exists
File.Move(oldFileName,newFileName); // Rename the oldFileName into newFileName
Run Code Online (Sandbox Code Playgroud)
或者用try catch包围它以避免异常.
Nog*_*gro 32
只需添加:
namespace System.IO
{
public static class ExtendedMethod
{
public static void Rename(this FileInfo fileInfo, string newName)
{
fileInfo.MoveTo(fileInfo.Directory.FullName + "\\" + newName);
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后...
FileInfo file = new FileInfo("c:\test.txt");
file.Rename("test2.txt");
Run Code Online (Sandbox Code Playgroud)
小智 20
第一解决方案
避免System.IO.File.Move在此处发布解决方案(包括标记答案).它失败了网络.但是,复制/删除模式在本地和网络上工作.请遵循其中一个移动解决方案,但请将其替换为Copy.然后使用File.Delete删除原始文件.
您可以创建一个Rename方法来简化它.
便于使用
在C#中使用VB程序集.添加对Microsoft.VisualBasic的引用
然后重命名文件:
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(myfile, newName);
两者都是字符串.请注意,myfile具有完整路径.newName没有.例如:
a = "C:\whatever\a.txt";
b = "b.txt";
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(a, b);
Run Code Online (Sandbox Code Playgroud)
该C:\whatever\文件夹现在将包含b.txt.
Zak*_*ury 16
您可以将其复制为新文件,然后使用System.IO.File该类删除旧文件:
if (File.Exists(oldName))
{
File.Copy(oldName, newName, true);
File.Delete(oldName);
}
Run Code Online (Sandbox Code Playgroud)
Maj*_*man 13
public void RenameFile(string filePath, string newName)
{
FileInfo fileInfo = new FileInfo(filePath);
fileInfo.MoveTo(fileInfo.Directory.FullName + "\\" + newName);
}
Run Code Online (Sandbox Code Playgroud)
注意:在此示例代码中,我们打开一个目录,并在文件名中搜索带有左括号和右括号的PDF文件.您可以检查并替换您喜欢的名称中的任何字符,或者使用替换函数指定一个全新的名称.
还有其他方法可以使用此代码进行更精细的重命名,但我的主要目的是展示如何使用File.Move进行批量重命名.当我在笔记本电脑上运行它时,这对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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用:
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);
Run Code Online (Sandbox Code Playgroud)
小智 6
用:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我找不到适合我的方法,所以我提出了我的版本。当然,它需要输入和错误处理。
public void Rename(string filePath, string newFileName)
{
var newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName + Path.GetExtension(filePath));
System.IO.File.Move(filePath, newFilePath);
}
Run Code Online (Sandbox Code Playgroud)
没有一个答案提到编写一个单元可测试的解决方案。您可以使用System.IO.Abstractions它,因为它提供了一个围绕 FileSystem 操作的可测试包装器,您可以使用它来创建模拟文件系统对象并编写单元测试。
using System.IO.Abstractions;
IFileInfo fileInfo = _fileSystem.FileInfo.FromFileName("filePathAndName");
fileInfo.MoveTo(Path.Combine(fileInfo.DirectoryName, newName));
Run Code Online (Sandbox Code Playgroud)
它已经过测试,并且是重命名文件的工作代码。