Search code examples
c#iisblazorserver-side

Blazor Server-Side download issues in IIS


I am trying to download a List of files (user has the option to select multiple). My current code below works fine in localhost (writing and opening the downloads folder). However, when I upload to IIS it gives an error saying that the system configuration is not found. Please see below:

if (SelectDownloadFiles.Count > 0)
{
    //Downloads folder (User profile)
    string DownloadFolder = Environment.ExpandEnvironmentVariables("%userprofile%/downloads/");

    //This is a little hack to get the literal path for the Downloads folder without too much of back-and-forth and ellaboration
    string FolderForward = DownloadFolder.Replace(@"/", @"\");
    string Folder = FolderForward.Replace(@"\\", @"\");

    foreach (var items in SelectDownloadFiles)
    {
        //Get Date
        var GetDate = items.Substring(0, 6);

        //Add 2 days to be consistent to what is displayed to the user (when files were generated)
        var FileDate = DateTime.ParseExact(GetDate, "yyMMdd", CultureInfo.InvariantCulture).AddDays(2);

        //Get Files
        string Pathname = @"D:\";
        string FullPathName = Path.Combine(Pathname, items);
        byte[] FileBytes = System.IO.File.ReadAllBytes(FullPathName);
        MemoryStream Ms = new MemoryStream(FileBytes);

        //Rename the file to become user friendly
        string DownloadPath = Path.Combine(DownloadFolder, "My Files " + FileDate.ToString("MM-dd-yyyy") + ".zip");

        //Write file(s) to folder
        FileStream File = new FileStream(DownloadPath, FileMode.Create, FileAccess.Write);
        Ms.WriteTo(File);
        File.Close();
        Ms.Close();
    }

    //Open Downloads Folder with files
    Process.Start("explorer.exe", Folder);
    navigationManager.NavigateTo("/default", true);

    //DisplayMessage.Show("File(s) successfully downloaded. Please check your “Downloads” folder to access your file(s).", "OK", "check");
}
else
{
    Toaster.Add("Please select at least one file to download.", MatToastType.Warning);
}

I've also tried to use the solution below to no avail:

 private readonly IWebHostEnvironment _webHostEnvironment;

    public YourController (IWebHostEnvironment webHostEnvironment)
    {
        _webHostEnvironment= webHostEnvironment;
    }

If I use the "folderoptionpath" and choose "MyDocuments" for instance, the files download to the root path of the files inside IIS. Is there anything else I need to be doing to get to this to work? Thanks in advance!


Solution

  • Well, after spending some time researching this, I was finally able to get it going. I ended up using a Nuget Package called BlazorFileSaver and it works just fine. Here's the repo: https://github.com/IvanJosipovic/BlazorFileSaver/blob/master/src/BlazorFileSaver.Sample/Pages/Index.razor I hope this can help someone else in the future.