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;
The name 'Server' does not exist in the current context
CodePudding user response:
Use System.IO.File.Open(path, FileMode, FileAccess) instead
var fileStream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read);
CodePudding user response:
So two things
Fileis an method on yourController. You need to use the full nameSystem.IO.File- In .NET Core you should inject
IWebHostEnvironmentand then callenvironment.ContentRootFileProvider.GetFileInfo("/key.crt").PhysicalPathto 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();

