2012-02-15 87 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