Answers:
看一下System.IO.File.Move,将文件“移动”到新名称。
System.IO.File.Move("oldfilename", "newfilename");
System.IO.File.Move(oldNameFullPath, newNameFullPath);
在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
或用try catch包围它,以避免出现异常。
只需添加:
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");
第一个解决方案
避免System.IO.File.Move
在此处发布解决方案(包括标记的答案)。它通过网络进行故障转移。但是,复制/删除模式可在本地和通过网络工作。请遵循一种移动解决方案,但将其替换为“复制”。然后使用File.Delete删除原始文件。
您可以创建一个重命名方法来简化它。
使用方便
在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);
该C:\whatever\
文件夹现在将包含b.txt
。
smb
)ftp
,ssh
或什么都纷纷命令/图元文件移动/重命名除非不允许(如只读)。
您可以将其复制为新文件,然后使用System.IO.File
该类删除旧文件:
if (File.Exists(oldName))
{
File.Copy(oldName, newName, true);
File.Delete(oldName);
}
注意:在此示例代码中,我们打开目录,并在文件名中使用带括号的圆括号搜索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();
}
}
}
希望!这将对您有所帮助。:)
public static class FileInfoExtensions
{
/// <summary>
/// behavior when new filename is exist.
/// </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);
}
}
采用:
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);
Using System.IO;
)吗?
就我而言,我希望重命名的文件的名称唯一,因此我在名称中添加了日期时间戳。这样,“旧”日志的文件名始终是唯一的:
if (File.Exists(clogfile))
{
Int64 fileSizeInBytes = new FileInfo(clogfile).Length;
if (fileSizeInBytes > 5000000)
{
string path = Path.GetFullPath(clogfile);
string filename = Path.GetFileNameWithoutExtension(clogfile);
System.IO.File.Move(clogfile, Path.Combine(path, string.Format("{0}{1}.log", filename, DateTime.Now.ToString("yyyyMMdd_HHmmss"))));
}
}
public static class ImageRename
{
public static void ApplyChanges(string fileUrl,
string temporaryImageName,
string permanentImageName)
{
var currentFileName = Path.Combine(fileUrl,
temporaryImageName);
if (!File.Exists(currentFileName))
throw new FileNotFoundException();
var extention = Path.GetExtension(temporaryImageName);
var newFileName = Path.Combine(fileUrl,
$"{permanentImageName}
{extention}");
if (File.Exists(newFileName))
File.Delete(newFileName);
File.Move(currentFileName, newFileName);
}
}
我遇到一种情况,当我不得不在事件处理程序中重命名文件时,这会触发任何文件更改(包括重命名),并且永远跳过我必须重命名的文件的重命名,方法是:
File.Copy(fileFullPath, destFileName); // both has the format of "D:\..\..\myFile.ext"
Thread.Sleep(100); // wait OS to unfocus the file
File.Delete(fileFullPath);
以防万一有人会出现这种情况;)
当C#没有某些功能时,我使用C ++或C:
public partial class Program
{
[DllImport("msvcrt", CallingConvention = CallingConvention.Cdecl, SetLastError = true)]
public static extern int rename(
[MarshalAs(UnmanagedType.LPStr)]
string oldpath,
[MarshalAs(UnmanagedType.LPStr)]
string newpath);
static void FileRename()
{
while (true)
{
Console.Clear();
Console.Write("Enter a folder name: ");
string dir = Console.ReadLine().Trim('\\') + "\\";
if (string.IsNullOrWhiteSpace(dir))
break;
if (!Directory.Exists(dir))
{
Console.WriteLine("{0} does not exist", dir);
continue;
}
string[] files = Directory.GetFiles(dir, "*.mp3");
for (int i = 0; i < files.Length; i++)
{
string oldName = Path.GetFileName(files[i]);
int pos = oldName.IndexOfAny(new char[] { '0', '1', '2' });
if (pos == 0)
continue;
string newName = oldName.Substring(pos);
int res = rename(files[i], dir + newName);
}
}
Console.WriteLine("\n\t\tPress any key to go to main menu\n");
Console.ReadKey(true);
}
}