I have tried two methods to open a zip file from internet explorer, but none works.
Method 1
<li>
IM User Guide
</li>
With this method, I can see the "Open" dialog box. If I click on "Open", it may be trying to open it. But the file is not opened.
Method 2
<li>
<asp:LinkButton ID="btnDownloadUserGuide" Text="IM User Guide" runat="server" Visible="true" OnClick="btnDownloadUserGuide_Click"></asp:LinkButton>
<asp:HiddenField ID="hdnUserGuide" runat="server" Value="~/HelpDocs/IMs_Guide.zip" /></li>
Code behind (Method 2)
protected void btnDownloadUserGuide_Click(object sender, EventArgs e)
{
if (!hdnUserGuide.Value.Trim().Equals(""))
{
//string strFileName = AppDomain.CurrentDomain.BaseDirectory.ToString() + "\\HelpDocs\\IMs_Guide.zip";
string FilePath = HttpContext.Current.Server.MapPath("\\HelpDocs\\IMs_Guide.zip");
string strFileName = AppDomain.CurrentDomain.BaseDirectory.ToString() + "\\HelpDocs\\IMs_Guide_to_New_Q-Track.zip";
Response.AppendHeader("content-disposition", "attachment; filename=" + "IMs_Guide.zip");
Response.AppendHeader("Cache-Control", "no-cache");
Response.ContentType = "Application/x-zip-compressed";
Response.WriteFile(FilePath);
//Response.End();
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
With this method, it may be trying to open it, but no "Open" dialog box is seen. File is not opened.
If attempt is made to save it instead of opening the file, that works.
The same issue is observed if the file type is changed to doc or pdf.
The same code (both methods) work in Chrome and Mozilla browsers.
Related
I have a form that on submit, downloads a generated csv file. I have an asp:Literal on the page as a placeholder for loading text:
<div id="loading-text">
<asp:Literal ID="litLoadingText" runat="server"></asp:Literal>
</div>
$("input[type=submit]").on("click", function() {
//$(".loading-modal").show();
$("#loading-text").html("Loading...");
});
and I'm trying to change the text after the download is complete to say "Done!" or just get removed:
Response.Clear();
Response.Buffer = true;
var fileName = !String.IsNullOrEmpty(txtFileName.Value) ? txtFileName.Value : "ContentExport";
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
litLoadingText.Text = "Done!";
}
but the text doesn't change. I'm pretty sure this is because of the downloading, where I'm doing Response.End() and whatnot, but I'm not sure how to handle it. Is there a way to do this in C#, or is there a Javascript method I could use instead to detect when the download is done? What would be the best approach?
The problem is described here: https://support.microsoft.com/en-us/help/312629/prb-threadabortexception-occurs-if-you-use-response-end-response-redir
Cause
The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.
This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.
Resolution
To work around this problem, use one of the following methods:
For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.
For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example:
Response.Redirect ("nextpage.aspx", false);
If you use this workaround, the code that follows Response.Redirect is executed.
For Server.Transfer, use the Server.Executemethod instead.
I am trying to view files from a folder in asp.net. I have tried using the "Response" class and its many functions to view files but so far I have been unsuccessful. Mostly using the Response class allows me to download the files but not view them in the browser. Most of what I have seen online suggests the same thing which is to use this bit of code:
string fileName = "Myfile.pdf";
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline; filename="+fileName);
But again, this only allows me to download the file and not view it in the browser.
Any suggestions on how I can do this?
This is what works for me:
Response.Clear();
Response.AddHeader("Content-Length", binaryFile.Length.ToString(CultureInfo.InvariantCulture));
//Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", title)); // save file as attachment
Response.AddHeader("Content-Disposition", string.Format("inline; filename={0}", title)); // display inline in browser
Response.AddHeader("Content-Type", "application/pdf");
Response.BinaryWrite(binaryFile);
Response.Flush();
Response.End();
Here is some nice project using free HTML based file browser:
https://github.com/magicbruno/FileBrowser
Alternative would be to use something like ASP.NET GridView and handle browsing specific folder. Here is short sample.
ASPX code:
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
Page code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DisplayDirectoryContent(Server.MapPath("~"));
}
}
void DisplayDirectoryContent(string directory)
{
System.Data.DataTable data = new System.Data.DataTable();
data.Columns.Add("Name",typeof(string));
data.Columns.Add("IsFolder", typeof(bool));
foreach (var dir in System.IO.Directory.GetDirectories(directory))
{
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(directory);
data.Rows.Add(new object[] { di.Name, true });
}
foreach (var file in System.IO.Directory.GetFiles(directory))
{
System.IO.FileInfo fi = new System.IO.FileInfo(file);
data.Rows.Add(new object[] { fi.Name, false });
}
GridView1.DataSource = data;
GridView1.DataBind();
}
Take notice that you cant directly view any file in browser, but you can link downolad action to GridView (similar to your code). This is how it works.
I have tried a code to open a pdf file in a web browser. It give to allows me to open the file through pdf reader no in the browser. Almost all the codes i found over the internet are also same as this code. But this code doesn't work as i expected.
Help me to figure out the problem in here. I'm using a link button in the aspx.
Here is my code
aspx code
<asp:LinkButton ID="pdfViewLOP" runat="server" Style="margin-left: 10px" OnClick="pdfViewLOP_Click" >View PDF</asp:LinkButton>
aspx.cs
Response.Write(string.Format("<script>window.open('{0}','_blank');</script>", "viewPDF.aspx"));
Code of the new page which pdf should be displayed
string name=Session["name"].ToString();
int refNo = Convert.ToInt32(name);
string FilePath = Server.MapPath("~/filesPDF/" + refNo + ".pdf");
WebClient User = new WebClient();
Byte[] buffer = User.DownloadData(FilePath);
if (buffer != null)
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
How if you directly create a hyperlink with target _blank and path of file as a href of hyperlink.
So the result hyperlink generated inside the html page is
View PDF
I am calling a function to return an Excel file and it is not opening in Excel, instead it is opening another tab in the browser. Here is my view:
#model InventoryControl.Models.AdminModel
<div>
#if (Model.TableCounts != null)
{
<table class="table_body">
<tr>
<th>#Html.DisplayNameFor(x=>x.TableCountModel.TableName)</th>
<th>#Html.DisplayNameFor(x=>x.TableCountModel.Rows)</th>
<th>#Html.DisplayNameFor(x=>x.TableCountModel.Count)</th>
<th>#Html.DisplayNameFor(x=>x.TableCountModel.Size)</th>
</tr>
#foreach (var item in Model.TableCounts)
{
<tr>
<td>
#item.TableName
</td>
<td>
#item.Rows
</td>
<td>
#item.Count
</td>
<td>
#item.Size
</td>
</tr>
}
</table>
}
else
{
<p><i>No data available</i></p>
}
</div>
<div>
#Html.ActionLink("Excel", "Excel")
</div>
Here is my controller function:
public void Excel()
{
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = ReportsRepository.TableCounts();
grid.DataBind();
Response.ClearContent();
Response.AddHeader("Content-Dispositon", "attachment; filename=TableCounts.csv");
Response.ContentType = "text/csv";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
I have looked in vain for an example that works and cannot find something that does.
If I make this change:
Response.AddHeader("Content-Dispositon", "attachment; filename=TableCounts.xlsx");
Response.ContentType = "application/vnd.ms-excel";
The file save/open dialog is fired but it says it is Excel 2003 format and the filename it says is "Excel".
Your code doesn't create an Excel file, it creates a CSV file. The content type isn't Excel-specific either. A browser may decide that Excel is the appropriate application to open this text file or not.
Even if the browser selects Excel, opening the file may fail, eg if the client's locale uses , as a decimal separator. This is common in European countries. In this case Excel expect ; as the field separator and may open the CSV as a single text block.
Instead of trying to trick the browser into opening a CSV in Excel, create a real Excel file using a library like EPPlus. EPPlus is available as a Nuget package so it's very easy to add it to your project.
The library's documentation contains an article on how to use it in Web applications. Once you remove the formatting code from the example, the code is very simple:
private void DumpExcel(DataTable tbl)
{
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(tbl, true);
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
}
Excel files are compressed which means that sending the file to the client will be a lot faster, especially for large files
Check your default program for opening csv files and set it to Excel.
I am trying to convert the gridview to excel and downloading the excel sheet to my computer's specific folder in my c# application.
The problem is: The file is getting downloaded at both the places.The destination folder and also the download folder.
the code for this is:
private void ExportToExcel(GridView GrdView, string fname)
{
Response.Clear();
Response.AddHeader("content-disposition", "inline;filename=" + fname + ".xls");
Response.Charset = "";
Response.ContentType = "application/OCTET-STREAM";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
string renderedGridView = stringWrite.ToString();
File.WriteAllText(#"C:\\Users\abc\\Desktop\" + fname + ".xls", renderedGridView);
Response.Write(stringWrite.ToString());
Response.End();
}
How to avoid the files getting downloaded to the download folder?
Please help!
Thank you
The answer would be to pick one: either render the control to a string and output to Response OR WriteAllText. If you want to use the WriteAllText to save the file to a determined location, then perform the action and pop up a notification to the user that the file was saved.