refactor: Common components are moved to the Common library.

This commit is contained in:
real-zony
2022-10-06 13:02:20 +08:00
parent ecab0e0f5c
commit 740e8f4c63
64 changed files with 84 additions and 150 deletions

View File

@@ -0,0 +1,65 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
using ZonyLrcTools.Common.Infrastructure.Exceptions;
using ZonyLrcTools.Common.Infrastructure.Extensions;
namespace ZonyLrcTools.Common.Infrastructure.IO
{
public class FileScanner : IFileScanner, ITransientDependency
{
public ILogger<FileScanner> Logger { get; set; }
public FileScanner()
{
Logger = NullLogger<FileScanner>.Instance;
}
public Task<List<FileScannerResult>> ScanAsync(string path, IEnumerable<string> extensions)
{
if (extensions == null || !extensions.Any())
{
throw new ErrorCodeException(ErrorCodes.FileSuffixIsEmpty);
}
if (!Directory.Exists(path))
{
throw new ErrorCodeException(ErrorCodes.DirectoryNotExist);
}
var files = new List<FileScannerResult>();
foreach (var extension in extensions)
{
var tempResult = new ConcurrentBag<string>();
SearchFile(tempResult, path, extension);
files.Add(new FileScannerResult(
Path.GetExtension(extension) ?? throw new ErrorCodeException(ErrorCodes.UnableToGetTheFileExtension),
tempResult.ToList()));
}
return Task.FromResult(files);
}
private void SearchFile(ConcurrentBag<string> files, string folder, string extension)
{
try
{
foreach (var file in Directory.GetFiles(folder, extension))
{
files.Add(file);
}
foreach (var directory in Directory.GetDirectories(folder))
{
SearchFile(files, directory, extension);
}
}
catch (Exception e)
{
Logger.LogWarningWithErrorCode(ErrorCodes.ScanFileError, e);
}
}
}
}