file deletion not working in asp.net vb - asp.net

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()

Related

Why the TransmitFile is not downlaoding the file?

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.

Excel File is corrupted when downloaded from Response Code in vb.net

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();

Convert excel file to byte array

I'm using ASP.net with VB codebehind.
I need to be able to convert an excel file created in code into a byte array in order to send it to the client. Without saving the file to the server.
this is how i created the excel document
Dim APP As Excel.Application = New Excel.Application
Dim missing As Object = System.Reflection.Missing.Value
Dim Workbook As Excel.Workbook = (APP.Workbooks.Add(missing))
Dim worksheet As Excel.Worksheet = Workbook.ActiveSheet
'..Fill cells in worksheet..
This is how i transmit it:
Response.Clear()
Response.ClearContent()
Response.ClearHeaders()
Response.Cookies.Clear()
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.CacheControl = "private"
Response.Charset = System.Text.UTF8Encoding.UTF8.WebName
Response.ContentEncoding = System.Text.UTF8Encoding.UTF8
Response.AppendHeader("Content-Length", filebytes.Length.ToString())
Response.AppendHeader("Pragma", "cache")
Response.AppendHeader("Expires", 60)
Response.AppendHeader("Conetnt-Disposition", "attachement; filename='MostIssuesByModelReport.xlsx'; size=" & filebytes.Length.ToString() & "; creation-date=" & Date.Now.ToString("R") & "; modification-date=" & Date.Now.ToString("R") & "; read-date=" & Date.Now.ToString("R"))
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
'write to client
Response.BinaryWrite(filebytes)
Response.End()
I just need to get the content of Workbook into filebytes
EDIT:
After looking around a bit more I can now make it download a file, however this file does not use the filename specified in the above code, it uses the name of the asp server page that the user is on, it also has a .aspx extension..however if I force it to open in excel it is correct. Besides popping up saying the source may be corrupted. Why is this happening and how can I fix it?

change aspx extension for pdf extension in Response.ContentType = "application/pdf"

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.

saving dataset in excel and allow user to download it in the client machine

I am developing an application where i want i am displaying a dataset in the datagrid view for the user.Now the user wants to download the data in the datagridview in an excel format.How can i do it ?
1) should i write the dataset in the excel and save it the server before the user download the file ?
2) Can i use a hyper link and set the path of the file that is saved in the server to the hyper link hRef property , so that the user can click and download the file ?
I am using C# ASP.net 2.0
Please help !
no need to save the file to the sever use the following code, will create the file on the fly:
Public Shared Sub DataTableToExcel(ByVal dt As DataTable, ByVal FileName As String
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.Write(Environment.NewLine)
For Each row As DataRow In dt.Rows
For i As Integer = 0 To dt.Columns.Count - 1
HttpContext.Current.Response.Write(row(i).ToString().Replace(";", String.Empty) + ";")
Next
HttpContext.Current.Response.Write(Environment.NewLine)
Next
HttpContext.Current.Response.ContentType = "application/ms-excel"
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls")
HttpContext.Current.Response.[End]()
End Sub
you can use this simple code to accomplish
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
string attachment = "attachment; filename=SummaryReport" + DateTime.Now.ToString() + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
grd.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
SpreadsheetGear for .NET will do it.
You can see ASP.NET (C# and VB) samples here and download a free trial here.
Disclaimer: I own SpreadsheetGear LLC

Resources