Reputation: 627
i am trying to use the following code in a page in my blazor app ( blazor server app)
@inject IWebHostEnvironment WebhostEnvironment
public IWebHostEnvironment _environment { get; set; }
var uploads = Path.Combine(_environment.WebRootPath, "uploads");
//string uploads = @"z:\Downloads";
path = uploads + "\\" + file.FileInfo.Name;
FileStream filestream = new FileStream(path, FileMode.Create, FileAccess.Write);
file.Stream.WriteTo(filestream);
filestream.Close();
file.Stream.Close();
to get files to save in an uploads folder within the wwwroot folder but when I execute the code I get ' object reference not set to an instance of an object'.
Questions 1.what is causing the error? 2.Is saving uploads in wwwroot subfolder the best route to go? 3. In a network server environment could a network path simply be set in a string variable as an alternative? When I uncomment the string uploads line above the upload is successful to the designated network drive on my home network.
Thanks for whatever information can be provided...
Upvotes: 8
Views: 20765
Reputation: 35
In my case (Blazor Server) I include this statement in my OnInitialized method:
rootpath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
rootpath is a private variable in the code block.
Then I use this approach to determine if I'm in debug mode (I work off the X: drive). The idea is, I want my code to work when I'm debugging or if the page is uploaded to the website.
if (rootpath.Contains("X:\\"))
{
rootpath = rootpath.Replace("bin\\Debug\\net6.0\\", "");
}
imagefullpath = rootpath + "\\Images\\Site\\AQ16.PNG";
Hope this helps.
Upvotes: 0
Reputation: 51
The current solution didn't work for me as I'm using Blazor wasm. The physical pathcan be found by accessing the AppDomain or AppContext:
string rootpath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
To access both you can use :
var b = $"Physical location {AppDomain.CurrentDomain.BaseDirectory}";
var c = $"AppContext.BaseDir {AppContext.BaseDirectory}";
Upvotes: 5
Reputation:
I assume we speak about "Blazor server-side".
The physical wwwroot folder may be found by:
string rootpath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot");
Saving uploaded files to a sub-dir of wwwroot is sometimes not optimal, as for security reasons, this place has to be read-only. Do your users need to download back uploaded files? If not, a temp folder outside the wwwroot will be a better place.
Network path? It's possible, but your web-application should run under credentials with read-write permissions on this place. Normally, web-applications run with restricted credentials.
In conclusion: your 2 last questions must be seen regarding security concerns.
Upvotes: 9