首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

帮忙写一个批量改名字步骤

2013-07-04 
帮忙写一个批量改名字方法!图片文件若干个名称大概是 1_2.jpg 11_12.jpg把名字修改为2_1.jpg12_11.jpg就是

帮忙写一个批量改名字方法!
图片文件若干个

名称大概是 1_2.jpg 11_12.jpg   

把名字修改为  2_1.jpg   12_11.jpg

就是把_前后的名称调换一下!    

谢谢!
[解决办法]


procedure TForm1.Button1Click(Sender: TObject);
var
   SearchRec:TSearchRec;
   found:integer;
   NameOld,NameNew:string;
   path:string;
   pos_1,pos_2:Integer;//_的位置,.的位置
   str1,str2,str3:string;//文件名分为三部分,_前面,.前面,.后面

begin
   path:='C:\Users\lenovo\Desktop\AutoCad资料\';
   found:=FindFirst(path+'*.*',faAnyFile,SearchRec);
   while    found=0    do
   begin
       if (SearchRec.Name<>'.')  and (SearchRec.Name<>'..')
             and    (SearchRec.Attr<>faDirectory)    then
       begin
         NameOld:=SearchRec.Name;
         pos_1:=pos('_',NameOld);
         pos_2:=pos('.',NameOld);
         str1:=leftstr(NameOld,pos_1-1);
         str2:=Copy(NameOld,pos_1+1,pos_2-pos_1-1);
         str3:=RightStr(NameOld,Length(NameOld)-pos_2);
         NameNew:=str2+'_'+str1+'.'+str3;
         RenameFile(path+NameOld,path+NameNew);
       end;
       found:=FindNext(SearchRec);
   end;
   FindClose(SearchRec);
end;

path写上你要改名目录,记得最后面写上'\'
[解决办法]

function MyRenameFile(const rootPath: string): string;
var
  valStr: string;
  liStr, liPath: TStringList;
  ser: tsearchRec;
  i: Integer;
begin
  liStr := TStringList.Create;
  liPath := TStringList.Create;
  try
    if FindFirst(rootPath + '*.jpg', faAnyFile, ser) = 0 then
      repeat
        liPath.Add(ser.Name);
      until (FindNext(ser) <> 0);
    if liPath.Count > 0 then
      for i := 0 to liPath.Count - 1 do
      begin
        valStr := StringReplace(liPath[i], '.jpg', '', [rfReplaceAll, rfIgnoreCase]);
        ExtractStrings(['_'], [], PChar(valStr), liStr);
        if liStr.Count > 1 then
        begin
          valStr := liStr[liStr.Count - 1] + '_' + liStr[liStr.Count - 2];


          RenameFile(rootPath + liPath[i], rootPath + valStr + '.jpg');
        end;
      end;
  finally
    FindClose(ser);
    liStr.Free;
    liPath.Free;
  end;
end;

// 调用
procedure TForm1.btn1Click(Sender: TObject);
begin
  MyRenameFile('C:\testtttt\'); // 路径最后要有'\'
end;

热点排行