random-file-runner/IO/SmartFileSystem.cs

167 lines
4.6 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
namespace RandomFileRunner.IO
{
public class SmartFileSystem
{
public static List<string> GetFiles(string path, string pattern)
{
List<string> fileList = new List<string>();
List<string> directoryList = new List<string>();
directoryList.Add(path);
while (true)
{
if (directoryList.Count <= 0)
{
break;
}
string directory = directoryList.First();
directoryList.RemoveAt(0);
if (IsDirectoryAccessible(directory))
{
IEnumerable<string> searchDirList = new List<string>();
try
{
searchDirList = Directory.EnumerateDirectories(directory, "*", SearchOption.TopDirectoryOnly);
}
catch (Exception)
{
continue;
}
foreach (string item in searchDirList)
{
if (!IsDirectoryAccessible(item))
{
continue;
}
directoryList.Add(item);
}
foreach (string item in Directory.EnumerateFiles(directory, pattern, SearchOption.TopDirectoryOnly))
{
if (!IsFileAccessible(item))
{
continue;
}
fileList.Add(item);
}
}
}
return fileList;
}
public static void GetFiles(string path, string pattern, Func<string, ulong, int, bool> callback)
{
List<string> directoryList = new List<string>();
ulong searchCount = 0;
directoryList.Add(path);
searchCount++;
while (true)
{
if (directoryList.Count <= 0)
{
break;
}
string directory = directoryList.First();
directoryList.RemoveAt(0);
callback(null, searchCount, directoryList.Count);
if (IsDirectoryAccessible(directory))
{
IEnumerable<string> searchDirList = new List<string>();
try
{
searchDirList = Directory.EnumerateDirectories(directory, "*", SearchOption.TopDirectoryOnly);
}
catch (Exception)
{
continue;
}
foreach (string item in searchDirList)
{
if (!IsDirectoryAccessible(item))
{
continue;
}
directoryList.Add(item);
searchCount++;
callback(null, searchCount, directoryList.Count);
}
foreach (string item in Directory.EnumerateFiles(directory, pattern, SearchOption.TopDirectoryOnly))
{
if (!IsFileAccessible(item))
{
continue;
}
callback(item, searchCount, directoryList.Count);
}
}
}
}
public static bool IsFileAccessible(string filename)
{
if (string.IsNullOrWhiteSpace(filename)) return false;
if (!File.Exists(filename)) return false;
try
{
FileInfo fi = new FileInfo(filename);
fi.GetAccessControl();
}
catch
{
return false;
}
return true;
}
public static bool IsDirectoryAccessible(string path)
{
if (string.IsNullOrWhiteSpace(path)) return false;
if (!Directory.Exists(path)) return false;
try
{
DirectoryInfo di = new DirectoryInfo(path);
di.GetAccessControl();
}
catch
{
return false;
}
return true;
}
}
}