剛好曲仔今天忽然有一個需求,說是從PC上可以看到聊天軟體Line的貼圖,網路上有教學如何找到且保存,只是要一個個重新命名。那我就想,能不能去自動化把所有檔案找出來,然後重新命名就好呢?所以今天下午就花點時間來寫個簡單應用。
這支程式的邏輯也很簡單,就幾個步驟:
- 先找到Line的快取路徑(一般在「使用者\AppData\Local\LINE\Cache」),整個Copy一份出來。怕誤動到原資料,所以Copy。
- 程式讀取選擇的資料夾當作Root,然後產生一個Rename資料夾存放結果。
- 遞迴讀取資料夾底下的每一層,每一個檔案
- 複製一份並更名,放到Rename資料夾
- 直到所有檔案複製完,完成
所以程式碼部份分成幾個部份:
- 顯示「瀏覽資料夾」的對話框,並印出選擇結果。我連ID都懶得重新命名。
- 用遞迴方式列舉檔案,這邊非常偷懶,把檔名和路徑分成兩個ArrayList存(因為一定每次兩個ArrayList都存到,所以之後用同樣index控制就好)。其實應該用一個struct包起來兩個參數,然後丟到一個List比較漂亮。
- 最後操作這兩個ArrayList,Copy & Rename & Paste一步搞定。
FolderBrowserDialog path = new FolderBrowserDialog(); path.ShowDialog(); this.textBox1.Text = path.SelectedPath;
private void GetFiles(DirectoryInfo di, string searchPattern, ref ArrayList MyFilesPath, ref ArrayList MyFilesName) { //取得檔案 foreach (FileInfo fi in di.GetFiles(searchPattern)) { //System.IO.File.Move(fi.FullName, fi.FullName+".png"); MyFilesPath.Add(fi.DirectoryName); MyFilesName.Add(fi.Name); } // Search in subdirctories foreach (DirectoryInfo d in di.GetDirectories()) { GetFiles(d, searchPattern, ref MyFilesPath, ref MyFilesName); //遞迴方法 } }
int listidx = 0; foreach (string s in MyFilesName) { //複製並更名 string tarstr = System.IO.Path.Combine(targetPath, s+".png"); string srcstr = System.IO.Path.Combine(MyFilesPath[listidx].ToString(), s); System.IO.File.Copy(srcstr, tarstr, true); //印出 this.textBox2.AppendText(s + "\n"); listidx++; }
當然我前面還有詢問是否要更名,建立新的資料夾等,這些都小事。整個程式碼自己只寫了不到40行,真的是有夠簡單@@。以後程序員會不會變成低薪行業啊?
程式畫面:
--完整Source Code(Visual Studio 2013 vaildated)
Download
0 意見:
張貼留言