Give folder selection option for download c# [duplicate] - c#

This question already has answers here:
How to implement a file download in asp.net
(2 answers)
Closed 4 days ago.
This post was edited and submitted for review 3 days ago.
I am converting multiple emf files to Vsdx files using c# and I wanted to download all converted vsdx files with zip file.
But instead of downloading directly I want it to open a download prompt to choose the location of file to be downloaded.
PS: I wanted to show the popup to select the path to download file
public ActionResult DownloadFile(string filePath)
{
string id = Convert.ToString(Session["id"]);
workingDirectory = HttpContext.Server.MapPath("~");
string fullpath = Path.Combine(workingDirectory, "output", id, "vsdx", filePath);
return File(fullpath, MimeTypes.GetMimeType(fullpath), Path.GetFileName(fullpath));
}

try this:
It will display a dialog box in the browser and the user will select on where to save the file
protected void DownloadFile_Click(object sender, EventArgs e)
{
String Filepath;
System.IO.FileInfo file = new System.IO.FileInfo(Filepath); // full file path on disk
Response.ClearContent(); // Clear previous content
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/pdf";
Response.TransmitFile(file.FullName);
Response.End();
}

Related

C# download button folder path

This question was migrated from Super User because it can be answered on Stack Overflow.
Migrated 14 days ago.
This is a C# code for a Web Form page named "upload.aspx" which allows the user to upload a PDF file and store it in the server. The file uploaded must be a PDF file, and all the text boxes must be filled before submission. The file name is saved in the database as a string with the format of "GUID.pdf", Guid.NewGuid().ToString().
tTR.FileName = Guid.NewGuid().ToString() + ".pdf";
dataBaseDataContext.TTRs.InsertOnSubmit(tTR);
dataBaseDataContext.SubmitChanges();
String path = Server.MapPath("Attachments/" + tTR.FileName);
FileUploadtoServer.SaveAs(path);
Response.Write("<script>alert('Successfully Inserted!')</script>");
Invoice.Text = "";
Manufacture.Text = "";
HeatCode.Text = "";
Description.Text = "";
PO_Number.Text = "";
i created a search function that allows the user to search for based on Heat Code, Item Code, PO Number, and Description. he user can also edit and download the file by clicking on the "Edit / Download" link. The problem here is in my Download button. It's not downloading/ able to read the path. i can see the pdf exist in the Attachment folder but it's not able to find the correct file name associated to the heat code.
private void BindData(List<TTR> Data)
{
try
{
if (Data.Count > 0)
{
StringBuilder append = new StringBuilder();
foreach (TTR tTR in Data)
{
string PdfGuid = tTR.FileName;
append.Append("
}
tdList.InnerHtml = append.ToString();
}
}
catch (Exception)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string filePath = Server.MapPath("~/Attachments/" + filename + ".pdf");
byte[] content = File.ReadAllBytes(filePath);
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + ".pdf");
Response.Buffer = true;
Response.BinaryWrite(content);
Response.End();
}
catch (Exception)
{
This is a C# code for a web form page named "upload.aspx" that allows a user to upload a PDF file, store it on the server, and save its file name in the database as a string with the format "GUID.pdf", where GUID is a unique identifier generated using Guid.NewGuid().ToString(). Before submission, all the text boxes must be filled, and the uploaded file must be a PDF.
The code also includes a search function that allows the user to search for files based on Heat Code, Item Code, PO Number, and Description. The user can also edit and download the file by clicking on the "Edit / Download" link. However, the download button is encountering issues as it is not able to find the correct file name associated with the heat code and download the file.
The problem seems to be with the code that retrieves the file path, reads the contents of the file, sets the content type as "application/pdf", and writes the contents to the response stream. The code is trying to read the file from the server's "Attachments" folder using the file path, but it seems to be encountering issues finding the correct file.

how to delete the downloaded file from server

I have created a mdb file,and zipping that file using asp.net and after that I am downloading the zip file.
After downloading file I just want to delete the file from the directory by using c#?
I just tried but the downloading is done after the button click exist but I want to download the file and after downloading it is deleted from the directory.
Have a example:
protected virtual void DownloadNDelete(string sFilePath, string sContentType)
{
string FileName = Path.GetFileName(sFilePath);
Response.Clear();
Response.AddHeader("Content-Disposition","attachment; filename=" + FileName);
Response.ContentType = sContentType;
Response.WriteFile(sFilePath);
Response.Flush();
this.DeleteFile(sFilePath);
Response.End();
}
This may help you
String filename=Directory.GetFile(#"c:\filename");
File.Delete(filename);
Have you tried this code?
string filename = "yourfilename";
if (filename != "")
{
string path = Server.MapPath(filename);
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
Response.Clear();
//Content-Disposition will tell the browser how to treat the file.(e.g. in case of jpg file, Either to display the file in browser or download it)
//Here the attachement is important. which is telling the browser to output as an attachment and the name that is to be displayed on the download dialog
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
//Telling length of the content..
Response.AddHeader("Content-Length", file.Length.ToString());
//Type of the file, whether it is exe, pdf, jpeg etc etc
Response.ContentType = "application/octet-stream";
//Writing the content of the file in response to send back to client..
Response.WriteFile(file.FullName);
Response.End();
// Delete the file...
System.IO.File.Delete(file.FullName);
}
else
{
Response.Write("This file does not exist.");
}
}

Cannot download exe files through c#.net

I have designed a website through which when i click a button a .EXE file should download from specific path from my computer.
But its not downloading the exe file instead its downloading the aspx page of the website.
I use the following code:
WebClient myWebClient = new WebClient();
// Concatenate the domain with the Web resource filename.
myWebClient.DownloadFile("http://localhost:1181/Compile/compilers/sample2.exe", "sample2.exe");
Can you please try this.
string filename = "yourfilename";
if (filename != "")
{
string path = Server.MapPath(filename);
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
Response.Clear();
//Content-Disposition will tell the browser how to treat the file.(e.g. in case of jpg file, Either to display the file in browser or download it)
//Here the attachement is important. which is telling the browser to output as an attachment and the name that is to be displayed on the download dialog
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
//Telling length of the content..
Response.AddHeader("Content-Length", file.Length.ToString());
//Type of the file, whether it is exe, pdf, jpeg etc etc
Response.ContentType = "application/octet-stream";
//Writing the content of the file in response to send back to client..
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}
I hope my edited comment will help to understand. But note: It is just a rough summary. You can do a lot more than this.

MVC C# Download file and save as dialog

Hi all wondering if someone can help; i've written this code which will generate an excel spreadsheet and save it to a specified location. I want to then display a "Save as" dialogue box by reading the file from the stored location and then asking then user where they want to store it. The excel file is being generated fine and i can open it normally! However my problem is the code i've written seems to be outputting the file directly to my browser, so i get all the contents of the excel file on my browser screen, not displaying the save as dialogue box as expected!
public ActionResult FormSuccess()
{
String FileName = System.Configuration.ConfigurationManager.AppSettings["FileName"].ToString();
String FilePath = System.Configuration.ConfigurationManager.AppSettings["FileSaveLocation"].ToString();
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.xls";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath + FileName);
response.End();
return PartialView("FormSuccess");
}
Yo Vince, how's tricks? Still wearing the medallion? :)
Shouldn't you be using FileContentResult instead of PartialView? You won't be able to return the file AND the HTML "success" content in the same call - you should probably call the PartialView first, which would then use javascript to open the FileContentResult URL in a new window.
See this: http://www.mikesdotnetting.com/Article/125/ASP.NET-MVC-Uploading-and-Downloading-Files
and this url as well :
http://weblogs.asp.net/rajbk/archive/2010/05/03/actionresult-types-in-mvc2.aspx
I think that your problem is that you return PartialView. Let me give you small exmaple of my implemetation:
public ActionResult FileXls()
{
var output = new MemoryStream();
var writer = new StreamWriter(output);
//create your workbook excel file
....
//workbook.Save(output);
writer.Flush();
output.Position = 0;
return File(output, "text/excel", "file.xls");
}

How to let the user to download an xml file

What i want to do is that the user selects some fields on a grid and according to these datas i create an xml file on the web server and then i want user to download it like downloading a any file. But the problem is, i cant use this code:
Response.ContentType = "APPLICATION/OCTET-STREAM";
// initialize the http content-disposition header to
// indicate a file attachment with the default filename
// "myFile.txt"
System.String disHeader = "Attachment; Filename=\"" + fileName +
"\"";
Response.AppendHeader("Content-Disposition", disHeader);
FileInfo downloadFile = new FileInfo(fileFullName);
if (downloadFile.Exists)
{
Response.WriteFile(downloadFile.FullName);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
Because i need to let the user download 3 files so the header cannot cary it, what i tought was getting the file names and open a popup, list the file names with a linkbutton, and then the user can download it.
For each file i create a linkbutton at runtime and add this code :
lnkProblem.Text = "Problemler dosyası";
lnkProblem.Visible = true;
lnkProblem.Command += new CommandEventHandler(lnkUser_Command);
lnkProblem.CommandName = Request.QueryString["fileNameProblems"];
lnkProblem.CommandArgument = Request.QueryString["fileNameProblems"];
Then use this function to make it download by the user :
void lnkUser_Command(object sender, CommandEventArgs e)
{
Response.ContentType = "APPLICATION/XML";
System.String disHeader = "Attachment; Filename=\"" + e.CommandArgument.ToString() +
"\"";
Response.AppendHeader("Content-Disposition", disHeader);
FileInfo downloadFile = new FileInfo(Server.MapPath(".") + "\\xmls\\" + e.CommandArgument.ToString());
if (downloadFile.Exists)
{
Response.WriteFile(Server.MapPath(".") + "\\xmls\\" + e.CommandArgument.ToString());
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
Application creates the xml file but somewhere of it, app puts the html tags in that xml file so i can't open the file, is there anyway to do this? Maybe any other example...
The cleaneast way to send a file to the client is to use the TransmitFile method like this:
FileInfo file = new FileInfo(filePath); // full file path on disk
Response.ClearContent(); // neded to clear previous (if any) written content
Response.AddHeader("Content-Disposition",
"attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/xml"; //RFC 3023
Response.TransmitFile(file.FullName);
Response.End();
For multiple files a common solution is to pack all files in a zip file and send them (the mime type would be application/zip in this case).
Create a separate IHttpHandler which would only serve files you want your users to download, and Redirect to that handler in lnkUser_Command.

Categories