(精华)2020年9月15日 ASP.NET Core 文件系统详解
1.文件系统遍历文件目录
public static class Sample01
{<!-- -->
public static void Run()
{<!-- -->
var provider = new ServiceCollection()
.AddSingleton<IFileProvider>(new PhysicalFileProvider(@"e:\测试文件夹"))
.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("");
}
}
}
2.程序内嵌文件读取文件信息
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);
return Encoding.Default.GetString(buffer);
}
}
}
3.监控文件系统,文件发生改变实时通知程序
public static class Sample03
{<!-- -->
public static void Run()
{<!-- -->
var provider = new ServiceCollection()
.AddSingleton<IFileProvider>(new PhysicalFileProvider(@"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);
return Encoding.Default.GetString(buffer);
}
}
}