Home > Software engineering >  FileStream Constructors in ASP.NET Core
FileStream Constructors in ASP.NET Core

Time:02-14

In ASP.NET, we can achieve this by FileStream.FileStream(string path, FileMode mode, FileAccess access); as below:

var fileStream = new FileStream(Server.MapPath("~/key.crt"), FileMode.Open, FileAccess.Read);
string text;
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
    text = streamReader.ReadToEnd();
}
Response response = new Response(text, samlTmp);

Can we achieve same in .NET Core? I need to pass file path and specify file mode along with the file read/write permission.

I have tried File.Open(). But I get this error even after adding the namespace using System.IO;

enter image description here

The name 'Server' does not exist in the current context

CodePudding user response:

Use System.IO.File.Open(path, FileMode, FileAccess) instead

https://docs.microsoft.com/fr-fr/dotnet/api/system.io.file.open?view=net-6.0#system-io-file-open(system-string-system-io-filemode-system-io-fileaccess)

var fileStream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read);

CodePudding user response:

So two things

  1. File is an method on your Controller. You need to use the full name System.IO.File
  2. In .NET Core you should inject IWebHostEnvironment and then call environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath to resolve the relative path to your key file.

All in all, your example could look like this instead

public IActionResult YourMethod([FromService]IWebHostEnvironment environment)
{
    var fileStream = System.IO.File.Open(environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath, FileMode.Open, FileAccess.Read);
    string text;
    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
    {
        text = streamReader.ReadToEnd();
    }
    Response response = new Response(text, samlTmp);
......

You should also be able to reduce

var fileStream = System.IO.File.Open(environment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPath, FileMode.Open, FileAccess.Read);

to

var fileStream = environment.ContentRootFileProvider.GetFileInfo("/key.crt").CreateReadStream();
  • Related