Подсчет хэшей всех файлов на диске С - C#
Формулировка задачи:
Добрый день! Пытаюсь вывести список всех файлов на компе с их MD5 хэшом, при подсчете хэша выскакивала ошибка "Процесс не может получить доступ к файлу, так как этот файл используется другим процессом", я попробовал поставить блок try{} catch(IOException){}, но теперь выводится лишь малая часть файлов. Подскажите пожалуйста, как это можно сделать.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Threading.Tasks;
using System.IO;
using System.Security.Cryptography;
using System.IO.Compression;
using Ionic.Zip;
using System.Threading;
namespace Md5_test1
{
class Program
{
private static string ComputeMD5Checksum(string path)
{
using (FileStream fs = System.IO.File.OpenRead(path))
using (MD5 md5 = new MD5CryptoServiceProvider())
{
byte[] checkSum = md5.ComputeHash(fs);
string result = BitConverter.ToString(checkSum).Replace("-", String.Empty);
return result;
}
}
static void Main(string[] args)
{
string logFile = (@"C:" + System.Net.Dns.GetHostName() + ".txt");
try
{
var filesname = from file in Directory.EnumerateFiles(@"C:", "*.*", SearchOption.AllDirectories)
select new
{
File = file,
};
foreach (var f in filesname)
{
try
{
File.AppendAllText(logFile, DateTime.Now.ToString("yyyy-MM-dd") + "||" + System.Net.Dns.GetHostName() + "||" + ComputeMD5Checksum(f.File) + "||" + Path.GetFileName(f.File) + "||" + f.File + "||" + GetSizeInString(FileSize(f.File)) + Environment.NewLine, Encoding.UTF8);
}
catch (IOException)
{
}
}
}
catch (UnauthorizedAccessException)
{
}
catch (PathTooLongException)
{
}
}
//Определение размера файла
private static long FileSize(string path)
{
//long Size = 0;
System.IO.FileInfo file = new System.IO.FileInfo(path);
long size = file.Length;
return (size);
}
//Привидение размера к килобайтам
private static string GetSizeInString(long size)
{
double temp = (double)size;
temp /= (1024);
return String.Format("{0:F}", temp) ;
}
}
}Решение задачи: «Подсчет хэшей всех файлов на диске С»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
namespace Md5_test1
{
class Program
{
private static List<string> mResult;
static void Main(string[] args)
{
DriveInfo di = new DriveInfo("C");
mResult = new List<string>();
ScanDirectorty(di.RootDirectory);
string logFile = Path.Combine(GetExeDirectory(), "log.txt");
using (var stream = new StreamWriter(logFile, false, Encoding.UTF8))
{
foreach (var item in mResult)
{
stream.WriteLine(item);
}
}
}
private static void ScanDirectorty(DirectoryInfo di)
{
try
{
foreach (var item in di.EnumerateFiles())
{
ScanFile(item);
}
foreach (var item in di.EnumerateDirectories())
{
ScanDirectorty(item);
}
}
catch (UnauthorizedAccessException)
{
mResult.Add(String.Format(
"Access denied to \t {0}",
di.FullName));
}
}
private static void ScanFile(FileInfo fi)
{
try
{
mResult.Add(String.Format(
"{0}\t{1}",
fi.FullName,
fi.Length));
}
catch (UnauthorizedAccessException)
{
mResult.Add(String.Format(
"Access denied to \t {0}",
fi.FullName));
}
}
private static string GetExeDirectory()
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
path = Path.GetDirectoryName(path);
return path;
}
}
}