72 lines
2.5 KiB
C#
72 lines
2.5 KiB
C#
using System;
|
|
using System.Collections.Frozen;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using winui_learning_3.Models;
|
|
|
|
namespace winui_learning_3.Services;
|
|
|
|
public class FolderContentService
|
|
{
|
|
private static readonly FrozenSet<string> TextExt =
|
|
new[] { ".txt", ".md", ".cs", ".json", ".xml", ".csv", ".log", ".xaml", ".html", ".css", ".js" }
|
|
.ToFrozenSet(StringComparer.OrdinalIgnoreCase);
|
|
|
|
private static readonly FrozenSet<string> ImageExt =
|
|
new[] { ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".svg", ".ico" }
|
|
.ToFrozenSet(StringComparer.OrdinalIgnoreCase);
|
|
|
|
private static readonly FrozenSet<string> VideoExt =
|
|
new[] { ".mp4", ".mkv", ".avi", ".mov", ".webm" }
|
|
.ToFrozenSet(StringComparer.OrdinalIgnoreCase);
|
|
|
|
private static readonly FrozenSet<string> AudioExt =
|
|
new[] { ".mp3", ".wav", ".flac", ".ogg", ".m4a" }
|
|
.ToFrozenSet(StringComparer.OrdinalIgnoreCase);
|
|
|
|
public static FolderContentDto GetFolderContent(string? path)
|
|
{
|
|
path ??= Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
|
|
var directory = new DirectoryInfo(path);
|
|
|
|
try
|
|
{
|
|
return new FolderContentDto
|
|
{
|
|
AbsolutePath = directory.FullName,
|
|
Files = [.. directory.EnumerateFiles().Select(ToFileDto)],
|
|
Children =
|
|
[
|
|
.. directory.EnumerateDirectories().Select(d => new FolderContentDto
|
|
{
|
|
AbsolutePath = d.FullName,
|
|
Files = [],
|
|
Children = []
|
|
})
|
|
]
|
|
};
|
|
}
|
|
catch (UnauthorizedAccessException ex)
|
|
{
|
|
throw new UnauthorizedAccessException($"Access to the path '{path}' is denied.", ex);
|
|
}
|
|
}
|
|
|
|
private static FileDto ToFileDto(FileInfo file) => new()
|
|
{
|
|
AbsolutePath = file.FullName,
|
|
Name = file.Name,
|
|
Extension = file.Extension,
|
|
Type = GetFileType(file.Extension)
|
|
};
|
|
|
|
private static FileTypeEnum GetFileType(string extension) => extension switch
|
|
{
|
|
_ when TextExt.Contains(extension) => FileTypeEnum.Text,
|
|
_ when ImageExt.Contains(extension) => FileTypeEnum.Image,
|
|
_ when VideoExt.Contains(extension) => FileTypeEnum.Video,
|
|
_ when AudioExt.Contains(extension) => FileTypeEnum.Audio,
|
|
".lnk" or ".url" => FileTypeEnum.Link,
|
|
_ => FileTypeEnum.Other
|
|
};
|
|
} |