ASP. NET Core 2.0 local file operation problems and solutions, asp. netcore

Source: Internet
Author: User

ASP. NET Core 2.0 local file operation problems and solutions, asp. netcore

Problem

In ASP. NET Core 2.0, how does one restrict access to local directories and file information?

Answer

Create an empty project, modify the Startup class, and add the services required to access local files:

public void ConfigureServices(IServiceCollection services){ services.AddSingleton<IFileProvider>(  new PhysicalFileProvider(Directory.GetCurrentDirectory()));}

Create a middleware, read all the files in the root directory, and output the file name:

public class HelloFileProviderMiddleware{ private readonly RequestDelegate _next; private readonly IFileProvider _fileProvider; public HelloFileProviderMiddleware(RequestDelegate next, IFileProvider fileProvider) {  _next = next;  _fileProvider = fileProvider; } public async Task Invoke(HttpContext context) {  var output = new StringBuilder("");  IDirectoryContents dir = _fileProvider.GetDirectoryContents("");  foreach (IFileInfo item in dir)  {   output.AppendLine(item.Name);  }  await context.Response.WriteAsync(output.ToString()); }}public static class UseHelloFileProviderExtensions{ public static IApplicationBuilder UseHelloFileProvider(this IApplicationBuilder app) {  return app.UseMiddleware<HelloFileProviderMiddleware>(); }}

Run:

Of course, we can also use the IFileProvider interface to read the information of a single file:

public class HelloFileProviderMiddleware{ private readonly RequestDelegate _next; private readonly IFileProvider _fileProvider; public HelloFileProviderMiddleware(RequestDelegate next, IFileProvider fileProvider) {  _next = next;  _fileProvider = fileProvider; } public async Task Invoke(HttpContext context) {  IFileInfo file = _fileProvider.GetFileInfo("Startup.cs");  using (var stream = file.CreateReadStream())  {   using (var reader = new StreamReader(stream))   {    var output = await reader.ReadToEndAsync();    await context.Response.WriteAsync(output.ToString());   }  } }}

Run:

Discussion

ASP. NET Core 2.0 provides the PhysicalFileProvider type inherited from the IFileProvider interface for restricted access to the local File System. It is an encapsulation of System. IO. File.

We can Configure IFileProvider as a service in Configure () method of Startup, and then add it to the middleware or controller through constructor injection. In this way, you can control the file access path (that is, when the application starts) in one place ).

IFileProvider has two important methods:

1. GetDirectoryContents: The IDirectoryContents interface is returned. It can be used to traverse all files or directories in a directory.

2. GetFileInfo: The IFileInfo interface is returned. The CreateReadSteam method can be used to read the file content.

===== Start by sanshi ===============================

The following uses recursion to traverse all files and directories under the root directory and modify the middleware code:

public class HelloFileProviderMiddleware{ private readonly RequestDelegate _next; private readonly IFileProvider _fileProvider; public HelloFileProviderMiddleware(RequestDelegate next, IFileProvider fileProvider) {  _next = next;  _fileProvider = fileProvider; } public async Task Invoke(HttpContext context) {  var output = new StringBuilder("");  ResolveDirectory(output, "", "");  await context.Response.WriteAsync(output.ToString()); } private void ResolveDirectory(StringBuilder output, string path, string prefix) {  IDirectoryContents dir = _fileProvider.GetDirectoryContents(path);  foreach (IFileInfo item in dir)  {   if (item.IsDirectory)   {    output.AppendLine(prefix + "[" + item.Name + "]");    ResolveDirectory(output,     item.PhysicalPath.Substring(Directory.GetCurrentDirectory().Length),     prefix + " ");   } else   {    output.AppendLine(prefix + item.Name);   }  } }} 

Run:

===== End by sanshi =============================

Source code download

Summary

The above is a small series of ASP. NET Core 2.0 local file operation problems and solutions, hope to help you, if you have any questions, please leave a message, xiaobian will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.