How to make the .xlsx file download - c#-2.0

The below is used to create the .xls file and download the file.
I want to download it to .xlsx file. If i simply change the extension into ".xlsx", the report directly opens in the browser. I want it to open in .xlsx extension. Kindly help me.
Below is the code reference for you,
//setting the application path to a variable
strPath = Server.MapPath("ExcelFiles");
//Creating a file name
strExportPath = "Card" + intRnd.ToString() + intRnd1.ToString() + ".xls";
hidFilePath.Value = "ExcelFiles/" + strExportPath;
//Creating the full path with the filename
strExcelPath = strPath + "\\" + strExportPath;
Session["AK_SC_CRD_EXCEL_PATH"] = strExcelPath;
StreamWriter objStreamWriter = new StreamWriter(strExcelPath, true);
//Write the XL Contents to a stream writer.
objStreamWriter.WriteLine(strXLContents);
objStreamWriter.Close();
objStreamWriter = null;
Thanks.

You may need to add a MIMETYPE for xslx to your response.
.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Similar to below;
Response.ContentType =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

Adding Following code will force your file download instead of opening in the browser.
Response.AddHeader("content-disposition", "attachment;filename=yourfilename.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
/*Add your code here to write file to response stream*/
Response.End();

Use following code to download Excel:-
HttpContext context = HttpContext.Current;
FileStream fs = null;
BinaryReader br = null;
byte[] data = null;
try
{
if (File.Exists(filePath))
{
FileInfo file = new FileInfo(filePath);
fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
br = new BinaryReader(fs, System.Text.Encoding.Default);
data = new byte[Convert.ToInt32(fs.Length)];
br.Read(data, 0, data.Length);
context.Response.Clear();
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AddHeader("content-disposition", "attachment; filename=" + file.FullName);
context.Response.AddHeader("Content-Length", file.Length.ToString());
context.Response.BinaryWrite(data);
context.Response.Flush();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

Related

path to resources directory in xamarin.android

I need the path to my resources directory to access my fonts folder inside it like the one in this code:
PdfFont russian = PdfFontFactory.createFont(
"src/main/resources/fonts/FreeSans.ttf", "CP1251", true);
but in Xamarin.android. I tried the following:
string uri = "android.resource://" + this.PackageName + "/font/ARIAL.TTF";
PdfFont russian = PdfFontFactory.CreateFont(
uri, "CP1251", true);
but it doesn't work. I tried this code too:
var path2 = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
filePath = System.IO.Path.Combine(path2.ToString(), "myfile4.pdf");
stream = new FileStream(filePath, FileMode.Create);
PdfWriter writer = new PdfWriter(stream);
PdfDocument pdf2 = new iText.Kernel.Pdf.PdfDocument(writer);
Document document2 = new Document(pdf2, PageSize.A4);
AssetManager assets = this.Assets;
string content;
Stream stream2 = assets.Open("ARIAL.TTF");
var memorystrm = new MemoryStream();
stream2.CopyTo(memorystrm);
byte[] t = memorystrm.ToArray();
Toast.MakeText(this, t.Length.ToString(), ToastLength.Long);
if (t != null)
{
PdfFont russian = PdfFontFactory.CreateFont(t, "UTF-8", true);
document2.SetFont(russian);
Paragraph p = new Paragraph("Hello World! ")
.Add(new Text("صباح! ").SetFontSize(14)).Add(new Text("Bonjour le monde! ").SetFontSize(10));
document2.Add(p);
document2.Close();
Toast.MakeText(this, "done", ToastLength.Long);
}
else
{
Toast.MakeText(this, "error", ToastLength.Long);
}
no code was exceuted
The path of the folder of the Xamarin.Android project is different with the native Android project.
If you want to save the font file in the project to access the file, try to save the files in the Asset folder.Set the Build Action for this files to AndroidAsset.
string content;
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader(assets.Open("read_asset.txt")))
{
content = sr.ReadToEnd();
}
Check the tutorial:
https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/resources-in-android/android-assets?tabs=windows
Update
i'll add my code, it didn't work. no code was executed
It seems that you forgot to add the .Show() code such as Toast.MakeText(this, "done", ToastLength.Long).Show().

ASP NET MVC and HTML5 audio - file not playing

I am trying to create a table containing audio files, which should start playing when the user clicks the play button. This is what I've tried so far:
Controller:
[HttpGet]
public ActionResult PlayFile(string FilePath)
{
WebClient WC = new WebClient();
WC.Credentials = new System.Net.NetworkCredential("username", "password");
byte[] buff = WC.DownloadData(FilePath);
var SplitFileName = FilePath.Split('\\');
string FileName = "Recording_" + SplitFileName[SplitFileName.Count() - 1];
Response.AddHeader("Content-Disposition", "inline; filename=" + FileName);
MemoryStream stream = new MemoryStream(buff);
return new FileStreamResult(stream, "audio/wav");
//I have also tried:
//return File(buff, "audio/wav");
}
The audio tags look like this:
<td>
<audio controls preload='none'>
<source src='/Components/PlayFile?FilePath=[filename.wav]' type='audio/wav'>
</audio>
</td>
When running the site locally in Chrome, all the files have the length 0:00, and you can click the play button once but the file is not played. After the play button has been clicked once it is not possible to click it again. It is however possible to download the file
and play it. When running the site locally in Firefox, the files also have the length 0:00, and when you click the play button the control disappears. It is also possible to download the file in Firefox. Does anyone know what could be causing this?
The problem was that the audio files were in GSM format and needed to be converted to PCM. This code works:
[HttpGet]
public ActionResult PlayFile(string FilePath)
{
WebClient WC = new WebClient();
WC.Credentials = new System.Net.NetworkCredential("username", "password");
byte[] buff = WC.DownloadData(FilePath);
var SplitFileName = FilePath.Split('\\');
string FileName = "Recording_" + SplitFileName[SplitFileName.Count() - 1];
MemoryStream ms = new MemoryStream();
ms.Write(buff, 0, buff.Length);
ms.Seek(0, SeekOrigin.Begin);
MemoryStream outputStream = new MemoryStream();
using (NAudio.Wave.WaveFileReader reader = new WaveFileReader(ms))
using (NAudio.Wave.WaveStream waveStream = NAudio.Wave.WaveFormatConversionStream.CreatePcmStream(reader))
using (NAudio.Wave.WaveFileWriter waveFileWriter = new WaveFileWriter(outputStream, waveStream.WaveFormat))
{
byte[] bytes = new byte[waveStream.Length];
waveStream.Position = 0;
waveStream.Read(bytes, 0, (int)waveStream.Length);
waveFileWriter.Write(bytes, 0, bytes.Length);
waveFileWriter.Flush();
}
return File(outputStream.ToArray(), "audio/wav");
}
Can you try with below as its working for me.
public FileResult PlayFile(string FilePath)
{
return new FilePathResult(FilePath, "audio/wav");
}
Also, try changing "audio/wav" to "audio/mp3", if it helps.

PDFSharp download file thru filestream

I am new to this library but I couldn't find anything about downloading to the filestream with this library, I could only find a document.Save(filepath) option which is not always allowed.
I would like to create a filestream so the file gets downloaded to the directed Downloads folder.
Could someone point me in the right direct?
There is a Save overload that takes a MemoryStream object instead of path to a file.
The PDFSharp website has an example showing how to do this:
private void Page_Load(object sender, System.EventArgs e)
{
// Create new PDF document
PdfDocument document = new PdfDocument();
this.time = document.Info.CreationDate;
document.Info.Title = "PDFsharp Clock Demo";
document.Info.Author = "Stefan Lange";
document.Info.Subject = "Server time: " +
this.time.ToString("F", CultureInfo.InvariantCulture);
// Create new page
PdfPage page = document.AddPage();
page.Width = XUnit.FromMillimeter(200);
page.Height = XUnit.FromMillimeter(200);
// Create graphics object and draw clock
XGraphics gfx = XGraphics.FromPdfPage(page);
RenderClock(gfx);
// Send PDF to browser
MemoryStream stream = new MemoryStream();
document.Save(stream, false);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", stream.Length.ToString());
Response.BinaryWrite(stream.ToArray());
Response.Flush();
stream.Close();
Response.End();
}

Error in converting HTML with images to PDF using itextsharp

In my application first am allowing the user to create html document using CKEDITOR where user can can create html document and can insert image, form fields etc. the generated HTML document is than converted into PDF.
If HTML document contains plain text than PDF file gets created successfully but if user inserts image in it than gives error.
code for creating PDF document.
public ActionResult CreateFile(FormCollection data)
{
var filename = data["filename"];
var htmlContent = data["content"];
string sFilePath = Server.MapPath(_createdPDF + filename + ".html");
htmlContent = htmlContent.Trim();
if (!System.IO.File.Exists(sFilePath))
{
using (FileStream fs = new FileStream(sFilePath, FileMode.Create))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.Write(htmlContent);
}
}
createPDF(sFilePath);
}
return View();
}
private MemoryStream createPDF(string sFilePath)
{
string filename = Path.GetFileNameWithoutExtension(sFilePath);
string name = Server.MapPath(_createdPDF + filename + ".pdf");
MemoryStream ms = new MemoryStream();
TextReader tr = new StringReader(sFilePath);
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
string urldir = Request.Url.GetLeftPart(UriPartial.Path);
urldir = urldir.Substring(0, urldir.LastIndexOf("/") + 1);
Response.Write(urldir);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(name, FileMode.Create));
document.Open();
string htmlText = "";
StreamReader sr;
sr = System.IO.File.OpenText(sFilePath);
htmlText = sr.ReadToEnd();
sr.Close();
WebClient wc = new WebClient();
Response.Write(htmlText);
var props = new Dictionary<string, Object>();
props["img_baseurl"] = #"C:\Documents and Settings\shubham\My Documents\visdatemplatemanger\visdatemplatemanger\";
List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(htmlText), null,props);
for (int k = 0; k < htmlarraylist.Count; k++)
{
document.Add((IElement)htmlarraylist[k]);
}
document.Close();
System.IO.File.Delete(sFilePath);
UploadURL(name);
return ms;
}
The error that i get if image is included in HTML document is:
Could not find a part of the path 'C:\Program Files\Common Files\Microsoft Shared\PDFimages\rectangle-shape.png'.
iTextSharp will try to resolve relative images for HTTP-based documents but ones served from the filesystem you need to either provide absolute paths or provide a base for it to search from.
//Image search base, path will be concatenated directly so make sure it contains a trailing slash
var props = new Dictionary<string, Object>();
props["img_baseurl"] = #"c:\images\";
//Include the props from above
htmlarraylist = HTMLWorker.ParseToList(sr, null, props);

ASP.NET MVC - How to dowload the .wmv file into our local file

How to download the file from server file to out local file system of type (.wmv) video file using Asp.net MVC pattern.
The files are existed in the Server File system in a cetain folder. The correponding file name existed in our local database.
Using Server's file system path + filename(.wmv) have to store into my local file system. please send me the links or code.
In your controller:
public void Open()
{
var serverfilepath = "some logical path";
var filename = "some file name";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.ContentType = "video/x-ms-wmv";
Response.Charset = "utf-8";
Response.HeaderEncoding = UnicodeEncoding.UTF8;
Response.ContentEncoding = UnicodeEncoding.UTF8;
var fi = new FileInfo(serverfilepath);
if ( fi.Exists )
{
using( var fs = fi.OpenRead() )
{
// you should really buffer this...
var bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int)fs.Length);
Response.BinaryWrite(bytes);
}
}
Response.End();
}

Resources