How to give a downloaded file unique name - c#

I have a C# application which saves a completed PDF file on a folder inside my site. During the operation I save two session variable to the filename and the filepath in the server:
string strFileName = "completed_pdf_" + k + ".pdf"; //k is a variable in a function for the name
Session["fileName"] = strFileName;
MessageBox.Show(Session["fileName"].toString()); //displays: completed_pdf_{name}.pdf
newFileServer = System.Environment.MachineName + #"/PDFGenerate/completed_pdf_" + k + ".pdf";
strFullPath = Path.GetFullPath("//" + newFileServer);
List<System.Web.UI.WebControls.ListItem> files = new List<System.Web.UI.WebControls.ListItem>();
files.Add(new System.Web.UI.WebControls.ListItem(strFullPath, strFullPath));
strN = files[0].ToString();
Session["pathName"] = strN;
MessageBox.Show(Session["pathName"].toString()); //displays: \\myserver\pdfgen\completed_pdf_{name}.pdf
I have a GridView which displays a LinkButton:
<asp:LinkButton ID="lnkDownload" Text = "Download" runat="server" OnClick = "DownloadFile" />
The function for the LinkButton is:
protected void DownloadFile(object sender, EventArgs e)
{
//MessageBox.Show(Session["pathName"].ToString()); //displays correctly
//MessageBox.Show(Session["fileName"].ToString()); //displays correctly
Response.Redirect("DownloadFilePDF.ashx?myvar=" + Session["pathName"].ToString() + "&myvar2=" + Session["fileName"].ToString());
}
My HTTPHandler code is this:
<%# WebHandler Language="C#" Class="DownloadFilePDF" %>
using System;
using System.Web;
public class DownloadFilePDF : IHttpHandler {
public void ProcessRequest (HttpContext context) {
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string strSessVar = request.QueryString["pathName"];
System.Web.HttpRequest request2 = System.Web.HttpContext.Current.Request;
string strSessVar2 = request.QueryString["fileName"];
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "attachment; filename=" + strSessVar + ";");
response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
When I run my website in the server itself, it asks me to download the ASHX file but if I run my website from my local PC which is on the same network as the server, it prompts me to download the PDF file. Everything is good so far, however, I am running into two issues:
The filename that is it downloading in my PC is DownloadFilePDF which is the HttpHandler filename.
The file is 0 Byte and when I open the file, it is not the right file type.
How can I fix so that..
The filename is the fileName QueryString I am sending to the HttpHandler file.
I can download the file which is residing in the server itself, so it's not 0 Byte.

How to give a downloaded file unique name
You can use couple of options, like the Guid class, DateTime.Now method and so on in order to have a unique identifier for the downloaded file, for example, use Guid.NewGuid:
response.AddHeader("Content-Disposition", "attachment; filename=" + string.format(strSessVar+{0}, Gui.NewGuid()) + ";");
UPDATE:
By using the following code you're doing nothing but sending an empty file:
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "attachment; filename=" + strSessVar + ";");
response.End();
In order to solve it, jst stream your file content to the response, look:
response.BinaryWrite(GetFileContentsFromSomewhere());

Something is amiss here. I don't see any content being streamed to the client. You need to provide the content in the response, like this:
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "attachment; filename=" + strSessVar + ";");
response.BinaryWrite(GetFileContentsFromSomewhere()); //<--- this baby does all the magic
response.End();
The GetFileContentsFromSomewhere() implementation depends on where you intend the file to come from. If it's just a static file on your web server, you could use something like this:
response.WriteFile(localPathOfFile);
or
response.WriteFile(Server.MapPath(urlOfFile));

Related

Save the generated file on Server instead of giving it as a download to user in C#

I have the following method, which converts HTML to Word Document and sends it as a download to user.
public static void HtmlToWordDownload(string HTML, string FileName, string title = "", bool border = false)
{
lock (LockMulti)
{
string strBody = string.Empty;
strBody = #"<html xmlns:o='urn:schemas-microsoft-com:office:office' " +
"xmlns:w='urn:schemas-microsoft-com:office:word'" +
"xmlns='http://www.w3.org/TR/REC-html40'>" +
"<head><title>:" + title + "</title>" +
"<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:Zoom>100</w:Zoom>" +
"<w:DoNotOptimizeForBrowser/></w:WordDocument></xml><![endif]-->" +
"<style> #page Section1 {size:8.27in 11.69in; mso-first-footer:ff1; mso-footer: f1; mso-header: h1; " +
((border == true) ? "border:solid navy 2.25pt; padding:24.0pt 24.0pt 24.0pt 24.0pt; " : "") +
"margin:0.6in 0.6in 0.6in 0.6in ; mso-header-margin:.1in; " +
"mso-footer-margin:.1in; mso-paper-source:0;} " +
"div.Section1 {page:Section1;} p.MsoFooter, li.MsoFooter, " +
"div.MsoFooter{margin:0in; margin-bottom:.0001pt; " +
"mso-pagination:widow-orphan; tab-stops:center 3.0in right 6.0in; " +
"font-size:12.0pt; font-family:'Arial';} " +
"p.MsoHeader, li.MsoHeader, div.MsoHeader {margin:0in; " +
"margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:center " +
"3.0in right 6.0in; font-size:12.0pt; font-family:'Arial';}--></style></head> ";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-word";
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + FileName + ".doc");
StringBuilder htmlCode = new StringBuilder();
htmlCode.Append(strBody);
htmlCode.Append("<body><div class=Section1>");
htmlCode.Append(HTML);
htmlCode.Append("</div></body></html>");
HttpContext.Current.Response.Write(htmlCode.ToString());
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
}
}
Now I don't want to give it as a download to user directly, I want to first save it on a local folder of my server and then give it as download. How do I do that?
You might try to serve the file you generate like this at the point that you do htmlCode.ToString():
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
Another method is save file and read it as a byte array and serve it like this:
byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();
or
string filename="Connectivity.doc";
if (filename != "")
{
string path = Server.MapPath(filename);
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}
Otherwise
Once you saved the word/pdf file on the server on some temp path you can use an HTTP Handler (.ashx) to download a file, like this:
ExamplePage.ashx:
public class DownloadFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition",
"attachment; filename=" + fileName + ";");
response.TransmitFile(Server.MapPath("FileDownload.csv"));
response.Flush();
response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Then you can call the HTTP Handler from the button click event handler, like this:
Markup:
<asp:Button ID="btnDownload" runat="server" Text="Download File"
OnClick="btnDownload_Click"/>
Code-Behind:
protected void btnDownload_Click(object sender, EventArgs e)
{
Response.Redirect("PathToHttpHandler/DownloadFile.ashx");
}
Passing a parameter to the HTTP Handler:
You can simply append a query string variable to the Response.Redirect(), like this:
Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");
Then in the actual handler code you can use the Request object in the HttpContext to grab the query string variable value, like this:
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];
// Use the yourVariableValue here
Note - it is common to pass a filename as a query string parameter to suggest to the user what the file actually is, in which case they can override that name value with Save As...

how to create zip and stock it in a link MVC or provide zip to user and redirect

I am able to create a zip with no problem, the only thing I cannot do, stock the zip file in a link so that when the user clicks on the link it will download the file
Response.Clear();
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=Photo.zip");
using (ZipFile zip = new ZipFile())
{
foreach (var pictures in pictureList)
{
zip.AddFile(Server.MapPath("~\\Content\\pictures\\upload\\" + pictures.name),"images");
}
zip.Save(Response.OutputStream);
}
Response.End();
Code below works for the file downloading.
public void DownloadFile(string fileName)
{
FileInfo file = new FileInfo(#"D:\DOCS\"+fileName);
Context.Response.Clear();
Context.Response.ClearHeaders();
Context.Response.ClearContent();
Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); Context.Response.AddHeader("Content-Length", file.Length.ToString());
Context.Response.ContentType = "application/zip";
Context.Response.Flush();
Context.Response.TransmitFile(file.FullName);
Context.Response.End();
}
However, Calling Response.Redirect after Response.End() will not going to work. If you really want to redirect the page you might have to think of an alternative way.

ASP.NET file download from server

After a user clicks a button, I want a file to be downloaded. I've tried the following which seems to work, but not without throwing an exception (ThreadAbort) which is not acceptable.
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
response.TransmitFile(Server.MapPath("FileDownload.csv"));
response.Flush();
response.End();
You can use an HTTP Handler (.ashx) to download a file, like this:
DownloadFile.ashx:
public class DownloadFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition",
"attachment; filename=" + fileName + ";");
response.TransmitFile(Server.MapPath("FileDownload.csv"));
response.Flush();
response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Then you can call the HTTP Handler from the button click event handler, like this:
Markup:
<asp:Button ID="btnDownload" runat="server" Text="Download File"
OnClick="btnDownload_Click"/>
Code-Behind:
protected void btnDownload_Click(object sender, EventArgs e)
{
Response.Redirect("PathToHttpHandler/DownloadFile.ashx");
}
Passing a parameter to the HTTP Handler:
You can simply append a query string variable to the Response.Redirect(), like this:
Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");
Then in the actual handler code you can use the Request object in the HttpContext to grab the query string variable value, like this:
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];
// Use the yourVariableValue here
Note - it is common to pass a filename as a query string parameter to suggest to the user what the file actually is, in which case they can override that name value with Save As...
Try this set of code to download a CSV file from the server.
byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();
Making changes as below and redeploying on server content type as
Response.ContentType = "application/octet-stream";
This worked for me.
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
Further to Karl Anderson solution, you could put your parameters into session information and then clear them after response.TransmitFile(Server.MapPath( Session(currentSessionItemName)));.
See MSDN page HttpSessionState.Add Method (String, Object) for more information on sessions.
protected void DescargarArchivo(string strRuta, string strFile)
{
FileInfo ObjArchivo = new System.IO.FileInfo(strRuta);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + strFile);
Response.AddHeader("Content-Length", ObjArchivo.Length.ToString());
Response.ContentType = "application/pdf";
Response.WriteFile(ObjArchivo.FullName);
Response.End();
}
Simple solution for downloading a file from the server:
protected void btnDownload_Click(object sender, EventArgs e)
{
string FileName = "Durgesh.jpg"; // It's a file name displayed on downloaded file on client side.
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "image/jpeg";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(Server.MapPath("~/File/001.jpg"));
response.Flush();
response.End();
}

Save dialog box to download file, Saving file from ASP.NET server to the client

I've been searching around the internet, but couldn't find any useful answer.
I have an ASP.NET web site, which is deployed on server.
The ASP.NET web site on the server can access a directory called W:/ .
The clients in the company can access the web site. The web site lists in a ListBox all the PDF files from the W:/ directory. The client should be able to select PDF files from the listbox and save them to it's local PC by selecting a location for it.
Something like save as file on web pages.
Could you provide me some solution or work around ?
Finally I've found an article, which Prompts a Save Dialog Box to Download a File from ASP.NET
I post it here, might help somebody else as well and save some time.
String FileName = "FileName.txt";
String FilePath = "C:/...."; //Replace this
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
This is an extension to user1734609's solution that gets a file locally.
To download a file from the server to client:
public void DownloadFile()
{
String FileName = "201604112318571964-sample2.txt";
String FilePath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/Uploads/" + FileName;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
}
The correct keywords are "File Browser asp.net" to find a lot of examples with source code.
Here is one from codeproject:
http://www.codeproject.com/Articles/301328/ASP-NETUser-Control-File-Browser
Get file contents in byte[] from W drive and write it to local file.
byte[] data = File.ReadAllBytes(WDriveFilePath)
FileStream file = File.Create(HttpContext.Current.Server.MapPath(MyLocalFile));
file.Write(data, 0, data.Length);
file.Close();
I have done something like this to get the file .
protected void btnExportFile_Click(object sender, EventArgs e)
{
try
{
Thread newThread = new Thread(new ThreadStart(ThreadMethod));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
// try using threads as you will get a Current thread must be set to single thread apartment (STA) mode before OLE Exception .
}
catch (Exception ex)
{
}
}
static void ThreadMethod()
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}

Open any file from asp.net

How can I open any file, specified by a path, in ASP.NET programatically?
I tried the snippet below but it reads the contents of the file instead of opening the file:
string fileName = #"C:\deneme.txt";
StreamReader sr = File.OpenText(fileName);
while (sr.Peek() != -1)
{
Response.Write(sr.ReadLine() + "<br>");
}
sr.Close();
I also tried the File.Open method.
You can Response.Redirect to file if you're just opeining it
or if file is being downloaded you can use the folling code;
public void DownloadFile(string fileName)
{
Response.Clear();
Response.ContentType = #"application\octet-stream";
System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(FileName));
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.Flush();
}
If you want the file to be opened on the client side,Create an HTTP Handler and set the appropriate mime type on your response before streaming it out from your handler.
for more information I ask question near to your one before.
how to open file with its application

Categories

Resources