How to get WebRootPath in asp.net mvc 5 - c#

I'm trying to implement this application in ASP.NET MVC 5
Export And Import Excel Data Using NPOI Library In .NET Core 2 Razor Pages
specifically, I'm trying this part which is to make the excel file downloadable one
So here my code for creating and downloading file
public FileResult OnPostExporttoExcel()
{
string webRootPath = _hostingEnvironment.WebRootPath;
string fileName = #"Testingdummy.xlsx";
string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, fileName);
FileInfo file = new FileInfo(Path.Combine(webRootPath, fileName));
var memoryStream = new MemoryStream();
// --- Below code would create excel file with dummy data----
using (var fs = new FileStream(Path.Combine(webRootPath, fileName), FileMode.Create, FileAccess.Write)) {
IWorkbook workbook = new XSSFWorkbook();
ISheet excelSheet = workbook.CreateSheet("Testingdummy");
IRow row = excelSheet.CreateRow(0);
row.CreateCell(0).SetCellValue("CustomerId");
row.CreateCell(1).SetCellValue("FirstName");
row.CreateCell(2).SetCellValue("LastName");
row.CreateCell(3).SetCellValue("Email");
cust = from s in _context.Customers select s;
int counter = 1;
foreach (var customer in cust) {
string FirstName = string.Empty;
if (customer.FirstName.Length > 100)
FirstName = customer.FirstName.Substring(0, 100);
else
FirstName = customer.FirstName;
row = excelSheet.CreateRow(counter);
row.CreateCell(0).SetCellValue(customer.CustomerId);
row.CreateCell(1).SetCellValue(FirstName);
row.CreateCell(2).SetCellValue(customer.LastName);
row.CreateCell(3).SetCellValue(customer.Email);
counter++;
}
workbook.Write(fs);
}
using (var fileStream = new FileStream(Path.Combine(webRootPath, fileName), FileMode.Open)) {
fileStream.CopyTo(memoryStream);
}
memoryStream.Position = 0;
return File(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
}
but I don't know how to get _hostingEnvironment.WebRootPath; in asp.net MVC 5

Related

C# - Trying to grab and save a pdf into my database

In my C# application, I am trying to make it able to pull a pdf and save it, so that end users can press a button and pull up that pdf while they are in the application. But when I copy the content to the filestream it makes the pdf but it is just blank with nothing from the original pdf. What am I doing wrong?
The pdf's could also have pictures on them, and I don't think the way I'm doing it would allow those to be brought over.
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
bool? response = openFileDialog.ShowDialog();
var fileContent = string.Empty;
var filestream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(filestream))
{
fileContent = reader.ReadToEnd();
}
// make folder path
string FolderPath = "ProjectPDFs\\";
string RootPath = "X:\\Vents-US Inventory";
DirectoryInfo FolderDir = new DirectoryInfo(Path.Combine(RootPath, FolderPath));
Directory.CreateDirectory(FolderDir.ToString());
string filePath = "";
string FileName = openFileDialog.SafeFileName;
if (fileContent.Length > 0)
{
filePath = Path.Combine(FolderDir.ToString(), FileName);
using (Stream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
byte[] bytestream = Encoding.UTF8.GetBytes(fileContent);
Stream stream = new MemoryStream(bytestream);
stream.CopyTo(fileStream);
}
}

iText7 pdf to blob c#

Using c# and iText7 I need to modify an existing PDF and save it to blob storage.
I have a console app that does exactly what I need using the file system:
PdfReader reader = new PdfReader(source);
PdfWriter writer = new PdfWriter(destination2);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
fields = form.GetFormFields();
fields.TryGetValue("header", out PdfFormField cl);
var type = cl.GetType();
cl.SetValue("This is a header");
pdfDoc.Close();
This works just fine. However I can not figure out how to do the same thing pulling the PDF from blob storage and sending the new one to blob storage
IDictionary<string, PdfFormField> fields;
MemoryStream outStream = new MemoryStream();
var pdfTemplate = _blobStorageService.GetBlob("mycontainer", "TestPDF.pdf");
PdfReader reader = new PdfReader(pdfTemplate);
PdfWriter writer = new PdfWriter(outStream);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
fields = form.GetFormFields();
fields.TryGetValue("header", out PdfFormField cl);
cl.SetValue("This is a header");
pdfDoc.Close();
outStream.Position = 0;
_blobStorageService.UploadBlobAsync("mycontainer", **THIS IS THE ISSUE**, "newpdf.pdf");
I think I need to get pdfDoc as a byte array. Outstream is incorrect, it is only has a length of 15
The code below shows how to read a PDF from a file into a byte[] and also how to modify a PDF that's stored as a byte[].
Download and install NuGet package: iText7
In Solution Explorer, right-click <project name> and select Manage NuGet Packages...
Click Browse
In the search box type: iText7
Select iText7
Select desired version
Click Install
Add the following using statements:
using System.IO;
using iText.Kernel.Pdf;
using iText.Forms;
using iText.Forms.Fields;
Get PDF as byte[] (GetPdfBytes):
public static Task<byte[]> GetPdfBytes(string pdfFilename)
{
byte[] pdfBytes = null;
using (PdfReader reader = new PdfReader(pdfFilename))
{
using (MemoryStream msPdfWriter = new MemoryStream())
{
using (PdfWriter writer = new PdfWriter(msPdfWriter))
{
using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
{
//don't close underlying streams when PdfDocument is closed
pdfDoc.SetCloseReader(false);
pdfDoc.SetCloseWriter(false);
//close
pdfDoc.Close();
//set value
msPdfWriter.Position = 0;
//convert to byte[]
pdfBytes = msPdfWriter.ToArray();
}
}
}
}
return Task.FromResult(pdfBytes);
}
Usage:
byte[] pdfBytes = null;
string filename = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "PDF File (*.pdf)|*.pdf";
if (ofd.ShowDialog() == DialogResult.OK)
{
//get PDF as byte[]
var tResult = GetPdfBytes(ofd.FileName);
pdfBytes = tResult.Result;
//For testing, write back to file so we can ensure that the PDF file opens properly
//create a new filename
filename = System.IO.Path.GetFileNameWithoutExtension(ofd.FileName) + " - Test.pdf";
filename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(ofd.FileName), filename);
//save to file
File.WriteAllBytes(filename, pdfBytes);
System.Diagnostics.Debug.WriteLine("Saved as '" + filename + "'");
}
Modify PDF that's stored in a byte[] (ModifyPdf)
public static Task<byte[]> ModifyPdf(byte[] pdfBytes)
{
byte[] modifiedPdfBytes = null;
using (MemoryStream ms = new MemoryStream(pdfBytes))
{
using (PdfReader reader = new PdfReader(ms))
{
using (MemoryStream msPdfWriter = new MemoryStream())
{
using (PdfWriter writer = new PdfWriter(msPdfWriter))
{
using (PdfDocument pdfDoc = new PdfDocument(reader, writer))
{
//don't close underlying streams when PdfDocument is closed
pdfDoc.SetCloseReader(false);
pdfDoc.SetCloseWriter(false);
//get AcroForm from document
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);
//get form fields
IDictionary<string, PdfFormField> fields = form.GetFormFields();
//for testing, show all fields
foreach (KeyValuePair<string, PdfFormField> kvp in fields)
{
System.Diagnostics.Debug.WriteLine("Key: '" + kvp.Key + "' Value: '" + kvp.Value + "'");
}
PdfFormField cl = null;
//get specified field
fields.TryGetValue("1 Employee name", out cl);
//set value for specified field
cl.SetValue("John Doe");
//close PdfDocument
pdfDoc.Close();
//set value
msPdfWriter.Position = 0;
//convert to byte[]
modifiedPdfBytes = msPdfWriter.ToArray();
}
}
}
}
}
return Task.FromResult(modifiedPdfBytes);
}
Usage:
byte[] pdfBytes = null;
string filename = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "PDF File (*.pdf)|*.pdf";
if (ofd.ShowDialog() == DialogResult.OK)
{
//get PDF as byte[]
var tResult = GetPdfBytes(ofd.FileName);
pdfBytes = tResult.Result;
//modify PDF
pdfBytes = await ModifyPdf(pdfBytes);
//create a new filename
filename = System.IO.Path.GetFileNameWithoutExtension(ofd.FileName) + " - TestModified.pdf";
filename = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(ofd.FileName), filename);
//save to file
File.WriteAllBytes(filename, pdfBytes);
System.Diagnostics.Debug.WriteLine("Saved as '" + filename + "'");
}
The code below is adapted from Sample01b_HelloWorldAsync.cs and is untested.
Download and install NuGet package: Azure.Storage.Blobs
Add the following using statement:
using Azure.Storage.Blobs;
DownloadPdf:
public static async Task<byte[]> DownloadPdf(string connectionString, string blobContainerName, string blobName)
{
byte[] pdfBytes = null;
using (MemoryStream ms = new MemoryStream())
{
// Get a reference to the container and then create it
BlobContainerClient container = new BlobContainerClient(connectionString, blobContainerName);
Azure.Response<Azure.Storage.Blobs.Models.BlobContainerInfo> responseCA = await container.CreateAsync();
// Get a reference to the blob
BlobClient blob = container.GetBlobClient(blobName);
// Download the blob's contents and save it to a file
Azure.Response responseDTA = await blob.DownloadToAsync(ms);
//set value
ms.Position = 0;
//convert to byte[]
pdfBytes = ms.ToArray();
}
return pdfBytes;
}
UploadPdf:
public static async Task<Azure.Response<Azure.Storage.Blobs.Models.BlobContentInfo>> UpdloadPdf(byte[] pdfBytes, string connectionString, string blobContainerName, string blobName)
{
Azure.Response<Azure.Storage.Blobs.Models.BlobContentInfo> result = null;
using (MemoryStream ms = new MemoryStream(pdfBytes))
{
//this statement may not be necessary
ms.Position = 0;
// Get a reference to the container and then create it
BlobContainerClient container = new BlobContainerClient(connectionString, blobContainerName);
await container.CreateAsync();
// Get a reference to the blob
BlobClient blob = container.GetBlobClient(blobName);
//upload
result = await blob.UploadAsync(ms);
}
return result;
}
Here's a PDF file for testing.

How to add existing file (image/mp4/pdf) to a ziparchive? - .Net Framework 4.6.2

I am trying to implement a "Download All" button that will zip up a selection of files from the server and return them as a zip file download. With the code below, I have the zip file being created. The expected files are inside, with the filenames expected, but the contents of the zipped files appears to be corrupted.
public ActionResult DownloadAll(Guid id)
{
var assets = db.InviteAssets.Include(i => i.AssetPages).Where(w => w.InviteID == id).ToList();
var cd = new System.Net.Mime.ContentDisposition
{
// for example foo.bak
FileName = "allAssets.zip",
// always prompt the user for downloading, set to true if you want
// the browser to try to show the file inline
Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
foreach (var asset in assets)
{
string path, extension, name;
if (asset.AssetType != AssetType.PDF)
{
path = asset.AssetPages.First(f => f.PageNumber == 1).FilePath;
}
else
{
path = string.Format("/Content/Assets/asset_{0}.pdf", asset.ID);
}
extension = path.Substring(path.IndexOf('.'));
name = "asset" + asset.Order + extension;
var file = archive.CreateEntry(name);
using (var streamWriter = new StreamWriter(file.Open()))
{
using (var fileStream = System.IO.File.Open(Server.MapPath("~" + path), FileMode.Open))
{
int filelength = (int)fileStream.Length;
var filedata = new byte[fileStream.Length];
streamWriter.Write(fileStream.Read(filedata, 0, filelength));
}
}
}
}
return File(memoryStream.ToArray(), "application/json", "allAssets.zip");
}
}
I'm thinking my issue is therefore with this section:
using (var streamWriter = new StreamWriter(file.Open()))
{
using (var fileStream = System.IO.File.Open(Server.MapPath("~" + path), FileMode.Open))
{
int filelength = (int)fileStream.Length;
var filedata = new byte[fileStream.Length];
streamWriter.Write(fileStream.Read(filedata, 0, filelength));
}
}
I keep reading examples that use a method archive.CreateEntryFromFile(filePath, fileName) but no such method is recognised. Has this been deprecated, or requires a higher version of .Net Framework?
Thanks in advance.
The problem is here:
streamWriter.Write(fileStream.Read(filedata, 0, filelength));
You’re reading the file contents into filedata but you’re at the same time writing the return value of Read into the archive, meaning a single int. You need to read and write separately:
fileStream.Read(filedata, 0, filelength));
streamWriter.Write(filedata, 0, filelength);
Or you can use the CreateEntryFromFile extension method in System.IO.Compression.ZipFileExtensions namespace.
I discovered that the reason I couldn't see the CreateEntryFromFile method was because I had not included a reference to System.IO.Compression.FileSystem. Once I added that, I could use CreateEntryFromFile which worked fine.
So now I have: archive.CreateEntryFromFile(Server.MapPath("~" + path), name);
Instead of:
var file = archive.CreateEntry(name);
using (var streamWriter = new StreamWriter(file.Open()))
{
using (var fileStream = System.IO.File.Open(Server.MapPath("~" + path), FileMode.Open))
{
int filelength = (int)fileStream.Length;
var filedata = new byte[fileStream.Length];
fileStream.Read(filedata, 0, filelength);
streamWriter.Write(filedata);
}
}

Use MergeFields to manipulate a word document with stream

This is the old code where copy to a local path, but now i need to save the file on SharePoint. How can i use stream with it and write the stream to file.
File.Copy(oTemplatePath, destinationPath, true);
using (WordprocessingDocument document = WordprocessingDocument.Open(destinationPath, true))
{
document.GetMergeFields("reference_number").ReplaceWithText(refrenceNumber);
document.MainDocumentPart.Document.Save();
for (int i = 0; i < newDoc.jsonFields.Count; i++)
{
if (newDoc.jsonFields[i].type == "date")
{
document.GetMergeFields(newDoc.jsonFields[i].controlName).ReplaceWithText(DateTime.Parse(newDoc.jsonFields[i].data).ToShortDateString());
document.MainDocumentPart.Document.Save();
}
else
{
document.GetMergeFields(newDoc.jsonFields[i].controlName).ReplaceWithText(newDoc.jsonFields[i].data);
document.MainDocumentPart.Document.Save();
}
}
//document.GetMergeFields(newDoc.jsonFields[i].controlName).ReplaceWithText(newDoc.jsonFields[i].data);
//document.MainDocumentPart.Document.Save();
}
You can save to local temp folder
string tempDocx = Path.Combine(Path.GetTempPath(), fileName);
logger.Trace($"Creating Word document {tempDocx}");
File.Delete(tempDocx);
File.Copy("Template.docx", tempDocx);
Then upload to SharePoint, here using a FileStream
using (IO.FileStream fs = new IO.FileStream(tempDocx, IO.FileMode.Open))
{
List documentsList = clientContext.Web.Lists.GetByTitle(libTitle);
clientContext.Load(documentsList.RootFolder);
clientContext.ExecuteQuery();
var fileCreationInformation = new FileCreationInformation();
//Assign to content byte[] i.e. documentStream
fileCreationInformation.ContentStream = fs;
//Allow owerwrite of document
fileCreationInformation.Overwrite = true;
//Upload URL
fileCreationInformation.Url = documentsList.RootFolder.ServerRelativeUrl + "/" + IO.Path.GetFileName(tempDocx);
uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation);
clientContext.Load(uploadFile);
clientContext.ExecuteQuery();
}

How to Save Excel File in a specific Folder

I am exporting excel file from database using following method.But i have one problem when i am exporting excel file than it is automatically downloading to download folder and i don't want this to be happen,I want my excel file to be downloaded in my project folder
var formsection = from fs in db.FormSections
join form in Form on fs.FormId equals form.FormId
select fs;
XLWorkbook wb = new XLWorkbook();
string sheetName = "ARTICLE"; //Give name for export file.
var Fs = wb.Worksheets.Add("FORMSECTION");
Fs.Cell(2, 1).InsertTable(formsection.ToList());// assign list here.
HttpContext.Response.Clear();
HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Response.AddHeader("content-disposition", String.Format(#"attachment;filename={0}.xlsx", sheetName.Replace(" ", "_")));
var filePath = Path.Combine(Server.MapPath("~/Content"));
using (MemoryStream memoryStream = new MemoryStream())
{
wb.SaveAs(memoryStream);
memoryStream.WriteTo(HttpContext.Response.OutputStream);
memoryStream.Close();
}
HttpContext.Response.End();
Here is an example that converts a datatable to a .csv file and save the file to the folder of your project for me its store the file in Domestic folder as the path given by me.
private void test(DataTable dt1) {
string csv = string.Empty;
foreach (DataColumn column in dt1.Columns)
{
//Add the Header row for CSV file.
csv += column.ColumnName + ',';
}
//Add new line.
csv += "\r\n";
foreach (DataRow row in dt1.Rows)
{
foreach (DataColumn column in dt1.Columns)
{
//Add the Data rows.
csv += row[column.ColumnName].ToString().Replace(",", ";") +',';
}
//Add new line.
csv += "\r\n";
}
string datetime = Convert.ToString(DateTime.Today.ToString("dd-MM-yyyy")).Trim();
string filepath = "C:\\Users\\Prateek\\Desktop\\MMR New 27-07 -\\Domestic\\";
string filename= #"BILLING_BOOK_NO" + "_4005" + "_"+datetime+".CSV";
string combinepath = filepath + filename;
System.IO.File.WriteAllText(combinepath,csv);
}`
You need to write the excel to your server first.
wb.SaveAs(filePath);
//encrypt the file
Encrypt(filePath);
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (MemoryStream memoryStream = new MemoryStream())
{
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
memoryStream.Write(bytes, 0, (int)file.Length);
memoryStream.WriteTo(HttpContext.Response.OutputStream);
}
}
use code as below
public void ImportXLX()
{
string filePath = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), #"C:\Users\Vipin\Desktop\Sheets\MyXL6.xlsx");
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath);
Request.Files["xlsFile"].SaveAs(filePath);
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
}

Categories

Resources