1. The file system traverses the file directory
public static class Sample01
{
public static void Run()
{
var provider = new ServiceCollection()
.AddSingleton<IFileProvider>(new PhysicalFileProvider(@"e:\ Test folder"))
.AddSingleton<FileManager>()
.BuildServiceProvider();
var fileManager = provider.GetService<FileManager>();
fileManager.Dir();
}
public class FileManager
{
private readonly IFileProvider _fileProvider;
public FileManager(IFileProvider fileProvider)
{
_fileProvider = fileProvider;
}
public void Dir()
{
var indent = - 1;
void Get(string subpath)
{
indent++;
foreach (var fileinfo in _fileProvider.GetDirectoryContents(subpath))
{
Console.WriteLine(new string('\t',indent) + fileinfo.Name);
if (fileinfo.IsDirectory)
{
Get($@"{subpath}\{fileinfo.Name}");
}
}
}
Get(""); }}}Copy the code
2. Program embedded file read file information
public static class Sample02
{
public static void Run()
{
var provider = new ServiceCollection()
.AddSingleton<IFileProvider>(new EmbeddedFileProvider(Assembly.GetExecutingAssembly()))
.AddSingleton<FileManager>()
.BuildServiceProvider();
var fileManager = provider.GetService<FileManager>();
var content = fileManager.ReadAsync("Text.txt").Result;
Console.WriteLine(content);
}
public class FileManager
{
private readonly IFileProvider _fileProvider;
public FileManager(IFileProvider fileProvider)
{
_fileProvider = fileProvider;
}
public async Task<string> ReadAsync(string path)
{
await using var stream = _fileProvider.GetFileInfo(path).CreateReadStream();
var buffer = new byte[stream.Length];
await stream.ReadAsync(buffer, 0, buffer.Length);
returnEncoding.Default.GetString(buffer); }}}Copy the code
3. Monitor the file system and notify the system of file changes in real time
public static class Sample03
{
public static void Run()
{
var provider = new ServiceCollection()
.AddSingleton<IFileProvider>(new PhysicalFileProvider(Other "@" e: \))
.AddSingleton<FileManager>()
.BuildServiceProvider();
var fileManager = provider.GetService<FileManager>();
fileManager.WatchAsync("Text.txt").Wait();
Console.Read();
}
public class FileManager
{
private readonly IFileProvider _fileProvider;
public FileManager(IFileProvider fileProvider)
{
_fileProvider = fileProvider;
}
public async Task WatchAsync(string path)
{
Console.WriteLine(await ReadAsync(path));
ChangeToken.OnChange(() => _fileProvider.Watch(path), async () =>
{
Console.Clear();
Console.WriteLine(await ReadAsync(path));
});
}
public async Task<string> ReadAsync(string path)
{
await using var stream = _fileProvider.GetFileInfo(path).CreateReadStream();
var buffer = new byte[stream.Length];
await stream.ReadAsync(buffer, 0, buffer.Length);
returnEncoding.Default.GetString(buffer); }}}Copy the code