我的任务是使用C#在一个文件夹中更改某些文件的名称(即,动态地为每个名称添加id).
示例:help.txt到1help.txt
我怎样才能做到这一点?
看看FileInfo.
做这样的事情:
void RenameThem() { DirectoryInfo d = new DirectoryInfo("c:/dir/"); FileInfo[] infos = d.GetFiles("*.myfiles"); foreach(FileInfo f in infos) { // Do the renaming here File.Move(f.FullName, Path.Combine(f.DirectoryName, "1" + f.Name)); } }
我将把它转储到这里,因为我需要为自己的目的编写这段代码.
using System; using System.IO; public static class FileSystemInfoExtensions { public static void Rename(this FileSystemInfo item, string newName) { if (item == null) { throw new ArgumentNullException("item"); } FileInfo fileInfo = item as FileInfo; if (fileInfo != null) { fileInfo.Rename(newName); return; } DirectoryInfo directoryInfo = item as DirectoryInfo; if (directoryInfo != null) { directoryInfo.Rename(newName); return; } throw new ArgumentException("Item", "Unexpected subclass of FileSystemInfo " + item.GetType()); } public static void Rename(this FileInfo file, string newName) { // Validate arguments. if (file == null) { throw new ArgumentNullException("file"); } else if (newName == null) { throw new ArgumentNullException("newName"); } else if (newName.Length == 0) { throw new ArgumentException("The name is empty.", "newName"); } else if (newName.IndexOf(Path.DirectorySeparatorChar) >= 0 || newName.IndexOf(Path.AltDirectorySeparatorChar) >= 0) { throw new ArgumentException("The name contains path separators. The file would be moved.", "newName"); } // Rename file. string newPath = Path.Combine(file.DirectoryName, newName); file.MoveTo(newPath); } public static void Rename(this DirectoryInfo directory, string newName) { // Validate arguments. if (directory == null) { throw new ArgumentNullException("directory"); } else if (newName == null) { throw new ArgumentNullException("newName"); } else if (newName.Length == 0) { throw new ArgumentException("The name is empty.", "newName"); } else if (newName.IndexOf(Path.DirectorySeparatorChar) >= 0 || newName.IndexOf(Path.AltDirectorySeparatorChar) >= 0) { throw new ArgumentException("The name contains path separators. The directory would be moved.", "newName"); } // Rename directory. string newPath = Path.Combine(directory.Parent.FullName, newName); directory.MoveTo(newPath); } }
您正在寻找的功能是File.Move(source, destination)
对的System.IO
命名空间.另外,请查看DirectoryInfo
该类(具有相同名称空间)以访问该文件夹的内容.