如何使用C#重命名文件? this
当C#没有某些功能时,我使用C ++或C: spa
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); } }
注意:在此示例代码中,咱们打开目录,并在文件名中使用带括号的圆括号搜索PDF文件。 您能够检查并替换您喜欢的名称中的任何字符,或者仅使用替换功能指定一个新的名称。 code
使用此代码还有其余方法能够进行更详细的重命名,但个人主要目的是演示如何使用File.Move进行批处理重命名。 当我在笔记本电脑上运行该文件时,它能够处理180个目录中的335个PDF文件。 这是对当前代码的刺激,还有更多复杂的方法能够执行此操做。 string
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(); } } }
在File.Move方法中,若是该文件已经存在,则不会覆盖该文件。 它将引起异常。 it
所以,咱们须要检查文件是否存在。 io
/* 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包围它,以免出现异常。 ast
只需添加: class
namespace System.IO { public static class ExtendedMethod { public static void Rename(this FileInfo fileInfo, string newName) { fileInfo.MoveTo(fileInfo.Directory.FullName + "\\" + newName); } } }
而后... pdf
FileInfo file = new FileInfo("c:\test.txt"); file.Rename("test2.txt");
使用: test
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);