Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8901

C# - .zi_ とか .ex_ とかの拡張子をリネームするツールつくった

$
0
0

メールの添付ファイルとして拡張子.zip.exeが禁止されている環境で、
ファイルをリネームして展開するのが地味に面倒なので、Drag&Dropでリネームするツールを作ってみた。
(※添付ファイルを開くときは慎重に!)

機能

Drag&Dropしたファイルの拡張子をリネームする。
拡張子の変換規則はプログラム内で決め打ちにしてある。

ソースコード

usingSystem;usingSystem.Collections.Generic;usingSystem.Drawing;usingSystem.IO;usingSystem.Windows.Forms;// Note: "."が2つ以上ある場合は、最後の"."以降を拡張子とみなす//  例: "hoge.tar.gz" の拡張子は "gz" とみなすclassFileRenamer:Form{staticDictionary<string,string>_defaultExtensionDict=newDictionary<string,string>(){// Key:変換前拡張子(小文字), Value:変換後拡張子// "."は付けない{"zi","zip"},{"zi_","zip"},{"ex","exe"},{"ex_","exe"},//{"",    "zip"},};FileRenamer(){Text="File Renamer";ClientSize=newSize(200,200);AllowDrop=true;DragEnter+=(sender,e)=>{if(e.Data.GetDataPresent(DataFormats.FileDrop)){e.Effect=DragDropEffects.Copy;}else{e.Effect=DragDropEffects.None;}};DragDrop+=(sender,e)=>{varfileNames=(string[])e.Data.GetData(DataFormats.FileDrop,false);foreach(stringsinfileNames){RenameFile(_defaultExtensionDict,s);}};}staticboolRenameFile(Dictionary<string,string>extentionConvertionDict,stringpartialFileName){varfi=newFileInfo(partialFileName);if(!fi.Exists){returnfalse;}stringnewName=GetRenamedFullName(extentionConvertionDict,fi);if(newName==null){returnfalse;}Console.WriteLine(newName);try{File.Move(fi.FullName,newName);}catch(UnauthorizedAccessExceptione){Console.WriteLine(e);}catch(PathTooLongExceptione){Console.WriteLine(e);}catch(DirectoryNotFoundExceptione){Console.WriteLine(e);}catch(IOExceptione){Console.WriteLine(e);}returntrue;}// return null : 変更対象ではない or エラーstaticstringGetRenamedFullName(Dictionary<string,string>extentionConvertionDict,FileInfofi){stringoldExtension;intposDot=fi.Name.LastIndexOf(".");if(posDot<0){// 拡張子がないoldExtension="";}elseif(posDot==0){// "."から始まっている(ファイル名部分がない)returnnull;}elseif(posDot==fi.Name.Length-1){// "."で終わっているreturnnull;}else{// posDot >= 1 (拡張子がある)oldExtension=fi.Name.Substring(posDot+1);// "."を含まない拡張子部分}oldExtension=oldExtension.ToLowerInvariant();// 小文字に変換するstringnewExtension;if(extentionConvertionDict.TryGetValue(oldExtension,outnewExtension)){returnPath.ChangeExtension(fi.FullName,newExtension);}else{returnnull;// 置換対象ではない}}[STAThread]staticvoidMain(string[]args){if(args.Length>=1){foreach(stringsinargs){RenameFile(_defaultExtensionDict,s);}}else{Application.Run(newFileRenamer());}}}

Viewing all articles
Browse latest Browse all 8901

Trending Articles