Save a file using IHttpContextAccessor

How to save a file using  IHttpContextAccessor in Dot Net Core project. How to initialize the 

 IHttpContextAccessor in Unit Test method.

For example in our prject , we have Controller  classes  >>>>>>   Service Classes >>>>>>  Helper CLassess where we are saving a file using HttpContext.Current in .Net framework but how to do the same process in .NetCore application.


I am not using any File Manager control, simply we read an xml file or pdf file and converting them to stream ,then we need to save in the Application hosted folder.


1 Reply

GK Gowthamraj Kumar Syncfusion Team May 6, 2022 02:53 PM UTC

Hi RAAJESH K A,


We have created the sample to generate the PDF document in subfolder of the wwwroot folder. Please try the below sample on your end and let us know the result.


string path = Path.Combine(_hostingEnvironment.ContentRootPath, "Data" , "Barcode.pdf");

 

FileStream str = new FileStream(path,FileMode.Open, FileAccess.Read);

//Load a PDF document.

PdfLoadedDocument document = new PdfLoadedDocument(str);

 

//Get first page from document

PdfLoadedPage page = document.Pages[0] as PdfLoadedPage;

 

//Create PDF graphics for the page

PdfGraphics graphics = page.Graphics;

 

//Set the standard font

PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);

 

//Draw the text

graphics.DrawString("Hello World!!!", font, PdfBrushes.Black, new PointF(0, 0));

 

//Saving the PDF to the MemoryStream

MemoryStream stream = new MemoryStream();

 

document.Save(stream);

 

//If the position is not set to '0' then the PDF will be empty.

stream.Position = 0;

 

string outputPath = Path.Combine(_hostingEnvironment.ContentRootPath, "wwwroot", "Sample.pdf");

//Save the PDF document in specific folder.

System.IO.File.WriteAllBytes(outputPath, stream.ToArray());


Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/CreatePdfFile-1882990177


Note: Above sample helps to save the PDF document in specific path location.


Please refer the below documentation to automatically download the files in browser location,

KB: https://www.syncfusion.com/kb/9137/how-to-create-a-pdf-file-in-asp-net-core

In above article, the file is always saved in 'Download' folder. It was controlled by the browser setting and the created PDF document was always saved in the download folder. Due to security purposes, we cannot change the saving path from the code snippet. So, we request you to change the specific folder on browser setting, Kindly refer the below link to get the more details,

https://support.google.com/chrome/answer/95759 
  


Please try the above sample on your end and let us know the result.

Regards,

Gowthamraj K


Loader.
Up arrow icon