I am downloading a file from folder but this code of me doesn't download. It doesn't throw any error but doesn't download either.
Dim req As WebClient = New WebClient()
Dim response As HttpResponse = HttpContext.Current.Response
Dim filePath As String = "~/Downloads/MyExcelFile.xls"
response.Clear()
response.ClearContent()
response.ClearHeaders()
response.Buffer = True
response.AddHeader("Content-Disposition", "attachment;filename=Filename.extension")
'Dim data As Byte() = req.DownloadData(Server.MapPath(filePath))
'response.BinaryWrite(data)
response.TransmitFile(Server.MapPath(filePath))
'response.End()
try
response.WriteFile("some file");
response.Flush();
response.Close();
also consider Andrew's response on handler type - ashx is usually cleaner, with webform you might have other things that happen during page life cycle.
Related
I am facing a strange error, i have a code in vb.net which basically just downloads an excel based on the dataset i have created. Everything seems to work fine and the file is downloaded but when i try to open the file, the file is corrupted.
I assume there is a problem in the code or maybe i am missing something, here is the code i am using:
dgGrid.DataSource = DS2.DefaultView ' This is where i do the Databinding
dgGrid.HeaderStyle.Font.Bold = True
dgGrid.DataBind()
ExcelFile = name & ".xls"
Response.Clear()
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", ExcelFile))
'Response.ContentType = "application/ms-excel"
Response.Charset = "utf-8"
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
'Response.ContentType = "application/octet-stream"
dgGrid.RenderControl(htwWriter)
Response.ContentEncoding = System.Text.Encoding.Unicode
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble())
Dim style As String = "<style>.textmode{mso-number-format:\#;}</style>"
Response.Write(style)
Response.Output.Write(stwWriter.ToString())
Response.End()
'Response.ContentType = "application/octet-stream"
Response.Close()
Response.Flush()
'Response.Write()
'Response.End()
Thanks, any help would be appreciated :(
Add the following line after flushing the file.
HttpContext.Current.Response.Close();
HttpContext.Current.Response.End();
I'm trying to download a file with size greater than 50mb in an asp.net page. But it fails on our production server. It works on development and QA servers. I'm using the following code.
Response.Clear()
oBinaryReader = New System.IO.BinaryReader(System.IO.File.OpenRead(sDocPath))
lFileSize = Microsoft.VisualBasic.FileLen(sDocPath)
Response.AddHeader("Content-Disposition", "attachment;filename=" & sDownloadFileName)
Response.ContentType = "application/unknown"
Response.BinaryWrite(oBinaryReader.ReadBytes(lFileSize))
Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
Response.End()
The error I'm getting from the server is as below.
Page_Load System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.IO.BinaryReader.ReadBytes(Int32 count)
at ExportDoc.Page_Load(Object sender, EventArgs e) in c:\sitename\ExportDoc.aspx.vb:line 87 Server Name
What is wrong with the code?
OutOfMemoryException commonly thrown when there is no available memory to perform such operation when handling both managed/unmanaged resources. Therefore, you need to use Using...End Using block wrapping around BinaryReader to guarantee immediate disposal of unmanaged resources after usage with IDisposable interface:
Response.Clear()
Using oBinaryReader As BinaryReader = New BinaryReader(File.OpenRead(sDocPath))
lFileSize = FileLen(sDocPath)
Response.AddHeader("Content-Disposition", "attachment;filename=" & sDownloadFileName)
Response.ContentType = "application/unknown"
Response.BinaryWrite(oBinaryReader.ReadBytes(lFileSize))
Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
Response.End()
End Using
Another common usage of BinaryReader is using FileStream and a byte buffer to control file reading mechanism:
Using FStream As FileStream = New FileStream(File.OpenRead(sDocPath))
lFileSize = CType(FStream.Length, Integer)
Dim Buffer() As Byte
Using oBinaryReader As BinaryReader = New BinaryReader(FStream)
Buffer = oBinaryReader.ReadBytes(lFileSize)
End Using
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment;filename=" & sDownloadFileName)
Response.ContentType = "application/unknown"
Response.BinaryWrite(Buffer)
Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
Response.End()
End Using
References:
VB.NET Using Statement (MSDN)
BinaryReader Class (MSDN)
I tried the below code and it resolved my issue, found the code idea from MSDN website.
Using iStream As System.IO.Stream = New System.IO.FileStream(sDocPath, System.IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
dataToRead = iStream.Length
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", "attachment; filename=" & filename)
While dataToRead > 0
If Response.IsClientConnected Then
length = iStream.Read(buffer, 0, bufferSize)
Response.OutputStream.Write(buffer, 0, length)
Response.Flush()
ReDim buffer(bufferSize)
dataToRead = dataToRead - length
Else
dataToRead = -1
End If
End While
HttpContext.Current.ApplicationInstance.CompleteRequest()
End Using
I am using following code for file deletion on server after downloading at client site.
The code is working from visual studio but NOT working when website is hosted even on the coding machine.
'To save the word file at temp location with unique name
Dim varDate As String = DateTime.Now.ToString("yyyyMMdd_hhmmss_fff")
Dim theFileName As String = Server.MapPath("~/Temp/Report_" & varDate & ".docx")
oWord.ActiveDocument.SaveAs(theFileName)
oWord.ActiveDocument.Close()
oWord.Quit()
Dim filefullname As System.IO.FileInfo = New System.IO.FileInfo(theFileName)
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=Observation_Report.docx")
Response.AddHeader("Content-Length", filefullname.Length.ToString())
Response.ContentType = "application/octet-stream"
Response.WriteFile(filefullname.FullName)
Response.Flush()
System.IO.File.Delete(theFileName)
Response.End()
I have a code that writes a pdf file into an aspx page, but the problem is that when I want to save this file it saves with aspx extension... for example:
It saves as myPDFfile.aspx and I want to save it as myPDFfile.pdf
and I have to change the extension to .pdf to be able to open it.
How can I change the extension programatically?
My code:
Dim pdfPath As String = path + Session("factura").ToString.Trim + ".pdf"
Dim client As New WebClient()
Dim buffer As [Byte]() = client.DownloadData(pdfPath)
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", buffer.Length.ToString())
Response.BinaryWrite(buffer)
You should add the Content-Disposition header :
Dim pdfPath As String = path + Session("factura").ToString.Trim + ".pdf"
Dim client As New WebClient()
Dim buffer As [Byte]() = client.DownloadData(pdfPath)
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", buffer.Length.ToString())
Response.AddHeader("content-disposition", "attachment; filename=myPDFfile.pdf")
Response.BinaryWrite(buffer)
You should also read this question and its answer as it will leads you to potential issue with filename characters.
You need to add a content-disposition header with the file name.
Response.AddHeader("content-disposition", "attachment; filename=myPDFfile.pdf");
This is part of RFC 2616, section 19.
Hi I am trying Export data to excel sheet from GridView but having this error.
RegisterForEventValidation can only be called during Render();
Here is my code
Dim attachment As String
attachment = "attachment; filename=Contacts.xls"
Response.ClearContent()
Response.AddHeader("content-disposition", attachment)
Response.ContentType = "application/ms-excel"
Dim myStringWriter As New IO.StringWriter
Dim myhtmlStringWriter As New HtmlTextWriter(myStringWriter)
GridView1.RenderControl(myhtmlStringWriter)
Response.Write(myStringWriter.ToString)
Response.End()
Thanks
You can do this in the web.config file but in this case the eventValidation will be turned off for all the pages.
or you can do this in the Page directive which will turn off the validation for a single page.