2012-02-15 53 views
0

該問題被標記爲ASP經典,但算法解決方案是好的。編號文件重命名算法

我有下面的一組文件被順序編號:

1.JPG,2.JPG,3.JPG,4.JPG ... X.jpg

我需要一個函數將輸入兩個文件名,fromFile和toFile參數,並且需要重命名所有需要的文件,以便在toFile之前的序列中移動from文件,並重新編號之間的文件。

例子:

移動1.JPG到4.JPG應做到以下幾點:

  • 重命名1.JPG到1.jpg.temp
  • 重命名2.JPG到1.JPG
  • 命名3.JPG到2.JPG
  • 命名1.jpg.temp到3.JPG
  • 其他文件不受影響由操作

移動4.JPG到2.JPG應做到以下幾點:

  • 重命名4.JPG到4.jpg.tmp
  • 重命名3.JPG到4.JPG
  • 更名2 .jpg文件到3.JPG
  • 重命名1.JPG到2.JPG
  • 命名4.jpg.tmp到1.JPG
  • 其他文件不受影響

作爲輸入我有一個字符串數組包含文件名和兩個文件名到/從。

你能告訴我什麼是文件重命名的最佳方法?

+0

好循環對文件進行檢查,檢查其名稱並進行更改是唯一方法(或者將它們添加到可排序的集合中然後重命名)。因爲這是asp,那麼大概有一個人可能會觸發這個,所以如果他們都在同一時間做這件事情會發生什麼。也許在txt/xml/db中定義的固定名稱和順序會更好 – 2012-02-15 16:39:15

+0

是的,我知道,但我有一項任務將此功能添加到甚至沒有數據庫的舊應用程序,並且他們使用了相應的數字文件...:/ – 2012-02-15 16:47:03

回答

1

下面是一個簡單的辦法,考慮到所有的文件將被命名爲numeric.jpg,你將不得不雖然建立自己的函數:

FileExists(Filename)
RenameFile(OriginalFilename,NewFilename)

<% 

Input1 = Request.Form("file1") 
Input2 = Request.Form("file2") 

'gets digits only 
Input1Digit = Left(Input1,Instr(Input1,".")) 
Input2Digit = Left(Input2,Instr(Input2,".")) 


'is file1 less than file2?    
If Input1Digit < Input2Digit Then  

    'loop through the digits frontwards 1 to 5 
    For x = Input1Digit to Input2Digit  

     'if the first loop? 
     If cStr(x) = cStr(Input1Digit) Then 

      'see if file exists here 
      If FileExists(Input1) Then 
       FileRename(Input1, Input1 & ".temp") 'Rename the file here [From, To] 
       OriginalFileExists = True 
      Else 
       FileRename(Input1, Input1Digit & ".jpg" 
       OriginalFileExists = False 
      End If 

     'if not on the first loop? 
     Else   

      'did the original file exist '.temp' 
      If OriginalFileExists Then 
       NewFileName = cInt(x) - 1 
      Else 
       NewFileName = cInt(x) 
      End If  

      'rename each file here 
      RenameFile(x & ".jpg", NewFileName & ".jpg") 

     End If  
    Next 

Else 


    'loop through the digits more to less 5 to 1 
    For x = Input1Digit to Input2Digit STEP -1  

     'if the first loop? 
     If cStr(x) = cStr(Input1Digit) Then 

      'see if file exists here 
      If FileExists(Input1) Then 
       FileRename(Input1, Input1 & ".temp") 'Rename the file here [From, To] 
       OriginalFileExists = True 
      Else 
       FileRename(Input1, Input1Digit & ".jpg" 
       OriginalFileExists = False 
      End If 

     'if not on the first loop? 
     Else   

      'did the original file exist '.temp' 
      If OriginalFileExists Then 
       NewFileName = cInt(x) + 1 
      Else 
       NewFileName = cInt(x) 
      End If  

      'rename each file here 
      RenameFile(x & ".jpg", NewFileName & ".jpg") 

     End If  
    Next 



End If 
%> 
+0

我認爲這會在最後的重命名文件之前錯過一個End If。當我將.tmp文件重新命名爲Input2時,這適用於例如1到4的移動。但是當向後移動文件4→1時它不起作用。它沒有在循環中抱怨,但似乎什麼都不做。 – 2012-02-16 12:27:17

+0

我忘了你必須做一個不同的FOR語句來進行背單詞計數,代碼已經更新,請告訴我。 – 2012-02-16 14:06:16

+0

差不多。它錯過了tmp的最終重命名爲新的文件名,但問題是,向後移動文件將其放在文件放在哪裏,然後放在文件後放在後面... – 2012-02-29 11:06:29