Rename a file in C#
如何使用c_重命名文件?
查看system.io.file.move,将文件"移动"到新名称。
1 | System.IO.File.Move("oldfilename","newfilename"); |
1 | System.IO.File.Move(oldNameFullPath, newNameFullPath); |
你可以用
在file.move方法中,如果文件已经存在,则不会覆盖该文件。它会抛出一个异常。
所以我们需要检查文件是否存在。
1 2 3 4 | /* 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包围它以避免异常。
只需添加:
1 2 3 4 5 6 7 8 9 10 | namespace System.IO { public static class ExtendedMethod { public static void Rename(this FileInfo fileInfo, string newName) { fileInfo.MoveTo(fileInfo.Directory.FullName +"\" + newName); } } } |
然后。。。
1 2 |
第一解
避免在此处发布
您可以创建一个重命名方法来简化它。
易用性
使用C_中的VB程序集。添加对Microsoft.VisualBasic的引用
然后重命名文件:
两者都是字符串。注意,myfile有完整的路径。newname没有。例如:
1 2 3 | a ="C:\whatever\a.txt"; b ="b.txt"; Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(a, b); |
您可以将其复制为新文件,然后使用
1 2 3 4 5 | if (File.Exists(oldName)) { File.Copy(oldName, newName, true); File.Delete(oldName); } |
注意:在这个示例代码中,我们打开一个目录,搜索文件名中带有打开和关闭圆括号的PDF文件。您可以检查和替换您喜欢的名称中的任何字符,或者使用replace函数指定一个全新的名称。
从这段代码中,还有其他方法可以更详细地进行重命名,但我的主要目的是演示如何使用file.move来进行批重命名。当我在笔记本电脑上运行它时,这对180个目录中的335个PDF文件有效。这是即时代码的刺激,而且还有更为复杂的方法来实现它。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 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(); } } } |
用途:
1 2 3 4 5 6 7 8 9 10 11 | using System.IO; string oldFilePath = @"C:\OldFile.txt"; // Full path of old file string newFilePath = @"C: ewFile.txt"; // Full path of new file if (File.Exists(newFilePath)) { File.Delete(newFilePath); } File.Move(oldFilePath, newFilePath); |
Hopefully! it will be helpful for you. :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | 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); } } |
如何使用此代码?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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); } } |
在我的例子中,我希望重命名文件的名称是唯一的,所以我在名称中添加了一个日期时间戳。这样,"旧"日志的文件名总是唯一的:
1 2 3 4 5 6 7 8 9 10 | 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")))); } } |
move执行相同的操作=复制并删除旧的。
1 | File.Move(@"C:\ScanPDF\Test.pdf", @"C:\BackupPDF" + string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.pdf",DateTime.Now)); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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); } } |
我找不到适合我的方法,所以我提出了我的版本。当然需要输入,错误处理。
1 2 3 4 5 | public void Rename(string filePath, string newFileName) { var newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName + Path.GetExtension(filePath)); System.IO.File.Move(filePath, newFilePath); } |
当C没有某些特性时,我使用C++或C:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 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(" \t\tPress any key to go to main menu "); Console.ReadKey(true); } } |