using System.Collections.Concurrent; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using YaeBlog.Core.Exceptions; using YaeBlog.Core.Models; namespace YaeBlog.Core.Services; public class EssayScanService( IOptions blogOptions, ILogger logger) { private readonly BlogOptions _blogOptions = blogOptions.Value; public async Task> ScanAsync() { string root = Path.Combine(Environment.CurrentDirectory, _blogOptions.Root); DirectoryInfo rootDirectory = new(root); if (!rootDirectory.Exists) { throw new BlogFileException($"'{root}' is not a directory."); } List markdownFiles = []; await Task.Run(() => { foreach (FileInfo fileInfo in rootDirectory.EnumerateFiles()) { if (fileInfo.Extension != ".md") { continue; } logger.LogDebug("Scan markdown file: {}.", fileInfo.Name); markdownFiles.Add(fileInfo); } }); ConcurrentBag contents = []; await Parallel.ForEachAsync(markdownFiles, async (info, token) => { StreamReader reader = new(info.OpenRead()); BlogContent content = new() { FileName = info.Name, FileContent = await reader.ReadToEndAsync(token) }; contents.Add(content); }); return contents.ToList(); } }