2013/02/15

C#でフォルダ内の全てのファイルのMD5を求める

GUIはコードからなんとなく想像できると思う。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Security.Cryptography;
namespace MD5Checker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void folderDialogButton_Click(object sender, EventArgs e)
{
//フォルダ指定ダイアログの表示
FolderBrowserDialog dialog = new
FolderBrowserDialog()
{
RootFolder = Environment.SpecialFolder.Desktop,
Description = "フォルダを選択してください"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
// 選択されたフォルダのパスをテキストボックスに表示
folderPathTextBox.Text = dialog.SelectedPath;
}
}
private void calculateMD5Button_Click(object sender, EventArgs e)
{
//指定されたフォルダが存在しない場合はメッセージを表示してメソッドを抜ける
if (!Directory.Exists(folderPathTextBox.Text))
{
MessageBox.Show("指定されたフォルダは存在しません");
return;
}
//結果出力ファイルの指定
SaveFileDialog saveFileDialog = new
SaveFileDialog()
{
Title = "保存ファイルを指定してください",
InitialDirectory = @"C:\",
Filter = "CSVファイル|*.csv"
};
//OKボタン以外がクリックされた場合はメソッドを抜ける
if (saveFileDialog.ShowDialog() != DialogResult.OK) return;
//結果をファイルに書き出す
using (StreamWriter writer = new StreamWriter(saveFileDialog.FileName))
{
foreach (string file in getAllFilePaths(folderPathTextBox.Text))
{
writer.Write(Path.GetDirectoryName(file));
writer.Write(",");
writer.Write(Path.GetFileName(file));
writer.Write(",");
writer.WriteLine(getMD5Hash(file));
}
}
MessageBox.Show("ファイルの出力が完了しました。");
}
//再帰的にファイルの一覧を取得する
private ArrayList getAllFilePaths(string topFolderPath)
{
ArrayList filePathList = new ArrayList();
foreach (string filePath in Directory.GetFiles(topFolderPath))
{
filePathList.Add(filePath);
}
foreach (string folderPath in Directory.GetDirectories(topFolderPath))
{
filePathList.AddRange(getAllFilePaths(folderPath));
}
return filePathList;
}
//ファイルのMD5ハッシュを算出する
private string getMD5Hash(string filePath)
{
//ファイルを読み込んでMD5ハッシュ値を算出する
byte[] hashValue = new MD5CryptoServiceProvider().ComputeHash(File.ReadAllBytes(filePath));
//ハイフンを除外して返す
return string.Join("", BitConverter.ToString(hashValue).Split('-'));
}
}
}
view raw MD5Checker.cs hosted with ❤ by GitHub