如何使用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);