2012-09-10 48 views
15

Tôi có hơn 1000 tệp trong thư mục có tên như abc_1, abc_2 ... abc_nĐổi tên tệp trong thư mục C#

Tôi muốn xóa tiền tố này 'abc_' khỏi tất cả các tệp. Bất kỳ cơ hội nào để không làm sổ tay này bởi vì chúng vượt quá 1000 và sẽ bị đau.

Làm cách nào để thực hiện việc này với C#?

+0

Có lẽ một ứng cử viên tốt cho một kịch bản Powershell –

+0

có một cái nhìn tại này http://stackoverflow.com/questions/2023975/renaming-a-directory-in-c-sharp –

+0

bạn chỉ muốn xóa các tiền tố ? – aliboy38

Trả lời

56

Bạn có thể thử với mã này

DirectoryInfo d = new DirectoryInfo(@"C:\DirectoryToAccess"); 
FileInfo[] infos = d.GetFiles(); 
foreach(FileInfo f in infos) 
{ 
    File.Move(f.FullName, f.FullName.Replace("abc_","")); 
} 
+0

Ồ, tôi đã trễ 10 giây. 1 cho DirectoryInfo và FileInfo – DoomerDGR8

+0

@Candie, cảm ơn bạn. Điều này làm việc hoàn hảo. –

+0

Tôi vui mừng được giúp bạn Jason, thak 'bạn –

2

Bạn có thể liệt kê các tập tin.

using System.IO; 

string[] filePaths = Directory.GetFiles(@"c:\MyDir\"); 

Sau đó, ForEach các string [] và tạo ra một thể hiện mới của đối tượng IO.File.

Khi bạn có được một xử lý trên Tệp, chỉ cần gọi phương thức Move và chuyển vào String.Replace ("abc_", String.Empty).

Tôi đã nói Di chuyển vì không có phương thức Đổi tên trực tiếp trong IO.File.

File.Move(oldFileName, newFileName);

Lưu ý đến phần mở rộng.

1

Total Commander có khả năng rename multiple files (Bạn không cần tự mình lập trình công cụ cho từng tác vụ nhỏ).

+0

Tôi thực sự không biết điều đó. Cảm ơn bạn! –

+0

Tôi không biết eather. Cảm ơn! –

1

Bạn có thể sử dụng File.MoveString.Substring(index):

var prefix = "abc_"; 
var rootDir = @"C:\Temp"; 
var fileNames = Directory.EnumerateFiles(rootDir, prefix + "*", SearchOption.AllDirectories); 
foreach(String path in fileNames) 
{ 
    var dir = Path.GetDirectoryName(path); 
    var fileName = Path.GetFileName(path); 
    var newPath = Path.Combine(dir, fileName.Substring(prefix.Length)); 
    File.Move(path, newPath); 
} 

Lưu ý: Directory.EnumerateFiles(rootDir, prefix + "*", SearchOption.AllDirectories); sẽ tìm kiếm các thư mục con cũng từ thư mục gốc của bạn. Nếu điều này không có ý định sử dụng SearchOption.TopDirectoryOnly.

2

Bạn nên xem phương thức DirectoryInfo và phương thức GetFiles(). Và hãy xem lớp File cung cấp phương thức Move().

File.Move(oldFileName, newFileName); 
1
string path = @"C:\NewFolder\";  
string[] filesInDirectpry = Directory.GetFiles(path, "abc*"); 
forearch(string file in filesInDirectory) 
{ 
    FileInfo fileInfo = new FileInfo(file); 
    fileInfo.MoveTo(path + "NewUniqueFileNamHere"); 
} 
3

mã sau đây sẽ làm việc, không được kiểm tra, mặc dù

public class FileNameFixer 
    { 
     public FileNameFixer() 
     { 
      StringToRemove = "_"; 
      StringReplacement = ""; 


     } 
     public void FixAll(string directory) 
     { 
      IEnumerable<string> files = Directory.EnumerateFiles(directory); 
      foreach (string file in files) 
      { 
       try 
       { 
        FileInfo info = new FileInfo(file); 
        if (!info.IsReadOnly && !info.Attributes.HasFlag(FileAttributes.System)) 
        { 
         string destFileName = GetNewFile(file); 
         info.MoveTo(destFileName); 
        } 
       } 
       catch (Exception ex) 
       { 
        Debug.Write(ex.Message); 
       } 
      } 
     } 

     private string GetNewFile(string file) 
     { 
      string nameWithoutExtension = Path.GetFileNameWithoutExtension(file); 
      if (nameWithoutExtension != null && nameWithoutExtension.Length > 1) 
      { 
       return Path.Combine(Path.GetDirectoryName(file), 
        file.Replace(StringToRemove, StringReplacement) + Path.GetExtension(file)); 
      } 
      return file; 
     } 

     public string StringToRemove { get; set; } 

     public string StringReplacement { get; set; } 
    } 

bạn có thể sử dụng lớp này như,

FileNameFixer fixer=new FileNameFixer(); 
     fixer.StringReplacement = String.Empty; 
     fixer.StringToRemove = "@@"; 
     fixer.FixAll("C:\\temp"); 
+0

Làm việc tốt :) Tôi đã thử nghiệm và sử dụng nó. – Sublime

-2

lệnh này sẽ làm các trick, sử dụng rename:

$ rename --find "abc_" * 
1

Tôi thích sự đơn giản của câu trả lời với số phiếu bầu cao nhất, nhưng tôi không muốn đường dẫn tệp bị sửa đổi nên tôi đã thay đổi mã một chút ...

string searchString = "_abc_"; 
string replaceString = "_123_"; 
string searchDirectory = @"\\unc\path\with\slashes\"; 
int counter = 0; 
DirectoryInfo d = new DirectoryInfo(searchDirectory); 
FileInfo[] infos = d.GetFiles(); 
foreach(FileInfo f in infos) 
{ 
    if (f.Name.Contains(searchString)) 
    { 
     File.Move(searchDirectory+f.Name, searchDirectory+ f.Name.Replace(searchString, replaceString)); 
     counter++; 
    } 
} 
Debug.Print("Files renamed" + counter); 
1

Mã này cho phép người dùng thay thế một phần tên tệp. Hữu ích nếu có nhiều tệp trong thư mục có cùng phần.

using System; 
using System.IO; 

// ... 
    static void Main(string[] args) 
    { 
     FileRenamer(@"D:\C++ Beginner's Guide", "Module", "PDF"); 

     Console.Write("Press any key to quit . . . "); 
     Console.ReadKey(true); 
    } 

    static void FileRenamer(string source, string search, string replace) 
    { 
     string[] files = Directory.GetFiles(source); 

     foreach (string filepath in files) 
     { 
      int fileindex = filepath.LastIndexOf('\\'); 
      string filename = filepath.Substring(fileindex); 

      int startIndex = filename.IndexOf(search); 
      if (startIndex == -1) 
       continue; 
      int endIndex = startIndex + search.Length; 

      string newName = filename.Substring(0, startIndex); 
      newName += replace; 
      newName += filename.Substring(endIndex); 

      string fileAddress = filepath.Substring(0, fileindex); 
      fileAddress += newName; 

      File.Move(filepath, fileAddress); 
     } 

     string[] subdirectories = Directory.GetDirectories(source); 
     foreach (string subdirectory in subdirectories) 
      FileRenamer(subdirectory, search, replace); 
    } 
Các vấn đề liên quan