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
Related
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();
}
}
}
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.
I want to export a file from a specific folder which the client will download. My code is below:
string Name = UserID + "HistoricalRecords.csv";
string fileName = "C:\\Temp\\"+Name;
TextWriter textWriter = new StreamWriter(fileName);
/*Some codes which add data to the csv.*/
byte[] bytes = Encoding.ASCII.GetBytes(textWriter.ToString());
if (bytes != null)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Content-Length", bytes.Length.ToString());
HttpContext.Current.Response.AppendHeader("Content-Disposition", "Attachment; Filename=" + fileName + "");
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
The file is created with the good content in the specified folder.
However, the file which the client is downloading is not the file from the specific folder "C:\Temp\" with the data as content. It is just creating a new file with the name= UserID + "HistoricalRecords.csv" and with no content. Any idea how to fix this?
You are not sending the file created to the client. Replace
HttpContext.Current.Response.BinaryWrite(bytes);
with
HttpContext.Current.Response.WriteFile(fileName);
Try this
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ContentType = "application/CSV";
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));
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();
}
}
}