Download stream to file - asp.net

I have a service which provides a stream. This stream should be written to a pdf-file.
I tried this method but it didn't work:
Using hcwHandler As IHealthCareWorkerServiceHandler = Container.CurrentContainer.Resolve(Of IHealthCareWorkerServiceHandler)()
stream = hcwHandler.DownloadPrescription(New DownloadPrescriptionRequest With {
.ProfessionCode = ucSelectProfession.ProfessionCode,
.RizivNumber = ucSelectProfession.Nihdi,
.Culture = language
}).Result
End Using
Dim buffer As Byte() = Encoding.ASCII.GetBytes(stream.ToString())
Using ms As New MemoryStream(buffer)
'write to file
Using file As New FileStream("prescription.pdf", FileMode.Create, FileAccess.Write)
ms.WriteTo(file)
End Using
End Using
I have tried several other solutions as well, but none seemed to work.
I never get a file.
Can anyone help me?

You can read the buffer (if there is data there) in a Using block without MemoryStream (like code below shows) and put a full absolute path like C:\Documents\PdfFolder\prescription.pdf
Using saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.InitialDirectory = "C:\Documents"
saveFileDialog1.RestoreDirectory = True
saveFileDialog1.Filter = "PDF files|*.pdf" ' change here for csv or xls
saveFileDialog1.FileName = "yourDefaultfileName.pdf"
If saveFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
If Len(saveFileDialog1.FileName.Length) > 0 Then
Try
Dim pdfPath As String = System.IO.Path.GetFullPath(saveFileDialog1.FileName)
Using file As New FileStream(pdfPath, FileMode.Create, FileAccess.Write)
file.Write(buffer, 0, buffer.Length)
End Using
MessageBox.Show("Saved in " & pdfPath)
Catch
MsgBox("Not a valid name file.")
End Try
End If
End If
End Using

And here a VB.NET version of How do I save a stream to a file in C#
Using fromWebFileStream As Stream = New StreamReader(yourStreamHere)
Using localFileStream As FileStream = File.Create("C:\Documents\PathTo\File")
'if you aren't at the begin of your stream uncomment this
'fromWebFileStream.Seek(0, SeekOrigin.Begin)
fromWebFileStream.CopyTo(localFileStream)
End Using
End Using

Related

Zipping an ExcelPackage in vb.net

I have created an excel document in code and I'm trying to zip the file using ZipArchive. I was attempting to do this by using BinaryReader/Writers but the the stream that I tried to make doesn't seem to contain anything. Any ideas what I'm doing wrong?
Using zip As ZipArchive = New ZipArchive(MemoryStream, ZipArchiveMode.Create, True)
Dim excelFile As ZipArchiveEntry = zip.CreateEntry("QueryExportTest.xlsx")
Using writer As BinaryWriter = New BinaryWriter(excelFile.Open())
Dim excelReader As BinaryReader = New BinaryReader(excel.Stream())
While excelReader.PeekChar() <> -1
writer.Write(excelReader.ReadBoolean)
End While
End Using
End Using
excel was defined earlier with Dim excel As New ExcelPackage()

VB.NET FTP Picture Upload Error [duplicate]

This question already has answers here:
Zip file is getting corrupted after downloading from server in C#
(3 answers)
Closed 4 years ago.
I am trying to allow authenticated users to upload pictures to the server through FTP. The code works for the most part. The part that doesn't is that there is an issue in uploading the file. I have tried to upload a few different pictures and all of them are larger on the server and therefore, not properly constructed.
One picture I tried is 4.56MB on my computer and 8.24MB on the server. When I load the picture in Photo, it states "We can't open this file." The page location is at http://troop7bhac.com/pages/slideshowedit.aspx. The following is the VB.NET code behind the upload:
Sub uploadFile_Click(sender As Object, e As EventArgs)
lblUploadErrors.InnerHtml = ""
If (lstSlideshowChoose.SelectedValue = "") Then
lblUploadErrors.InnerHtml = "<p>A slideshow must be selected.</p>"
Else
If (FileUpload1.HasFile) Then
Dim nameList() As String
Dim successList() As String
Dim i As Integer = 0
For Each file As HttpPostedFile In FileUpload1.PostedFiles
Dim fileBytes() As Byte = Nothing
Dim fileName As String = Path.GetFileName(file.FileName)
Dim photoRE As New Regex("^[A-z0-9 _]{1,}\.jpg|JPG|jpeg|JPEG|png|PNG+$")
Dim photoSuccess As Boolean = photoRE.Match(fileName).Success
ReDim Preserve nameList(i)
ReDim Preserve successList(i)
If (photoSuccess = True) Then
Using fileStream As New StreamReader(file.InputStream)
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd())
fileStream.Close()
End Using
Try
Dim request As FtpWebRequest = DirectCast(WebRequest.Create(ftpPath & lstSlideshowChoose.SelectedValue & "/" & fileName), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.UploadFile
request.Credentials = New NetworkCredential(ftpUser, ftpPass)
Using uploadStream As Stream = request.GetRequestStream()
uploadStream.Write(fileBytes, 0, fileBytes.Length)
uploadStream.Close()
End Using
Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
response.Close()
successList(i) = "Success "
Catch ex As Exception
successList(i) = "Failed "
End Try
Else
successList(i) = "Failed "
End If
nameList(i) = fileName
i += 1
Next
For x As Integer = 0 To nameList.Count - 1
lblUploadErrors.InnerHtml += "<p>" & successList(x) & nameList(x) & "</p>"
Next
Else
lblUploadErrors.InnerHtml = "<p>You have not selected a picture to upload.</p>"
End If
End If
End Sub
The files are obtained through an ASP.NET FileUpload control. The control has been set to allow multiple files at once.
Any help to figure out why the pictures are not uploading properly would be greatly appreciated.
EDIT: I tried Martin Prikryl's possible duplicate solution. Had to change it from C# to VB.NET. It failed. I tried David Sdot's solution and it also failed. Both solutions returned the same errors.
If the page was ran on my local machine, it returned "C:\Program Files (x86)\IIS Express\PictureName.JPG." If the page was ran on the server, it returned "C:\Windows\SysWOW64\inetsrv\PictureName.JPG." Both errors are of the System.IO.FileNotFoundException class.
Your Problem is here:
Using fileStream As New StreamReader(file.InputStream)
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd())
fileStream.Close()
Using
Your image is read as text. From this text you get the bytes UTF8 byte values, thats why your image is nearly twice the size when uplaoded. You need the bytes from the image, without converting them to something else.
fileBytes = File.ReadAllBytes(file.FileName)

How to Edit Excel with EPPLUS and send it as attachment

i have the following code, which it is working, it opens a file stream from an embedded Xlsx saves it on a memorystream then pass the value to the attachment and send it with no problem.
Private Sub SendFile2()
Dim path As String = Server.MapPath("~/App_Data/RQM.xlsx")
Using fileST As FileStream = IO.File.OpenRead(path)
Dim memStream As New MemoryStream()
memStream.SetLength(fileST.Length)
fileST.Read(memStream.GetBuffer(), 0, CInt(fileST.Length))
'' Code for MailMessage and SMTP goes here
MailMsg.Attachments.Add(New Attachment(memStream, "myFile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
End Using
End Using
End Sub
Now im trying to do some edition (adding some values to that file, but still working in a memorystream) but i am having some problems
i've added
Using pck As ExcelPackage = New ExcelPackage(memStream)
Dim xlswb As ExcelWorkbook = pck.Workbook
Dim xlsws As ExcelWorksheet = xlswb.Worksheets.First
xlsws.Cells(20, 4).Value = "HELLO WORLD"
pck.SaveAs(memStream)
End Using
Which when i put breakpoints i see pck getting the value of MemStream with a lenght of 83084 (the value of the original file) 81kb xlsx, when i add the value to the cell the lenght of memStream is 162143 so it seems it does some modifications, however when i send again the memstream trough
MailMsg.Attachments.Add(New Attachment(memStream, "myFile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
i receive a file of 165b, and i'm not sure what i am doing wrong.
Any help would be apreciated
Edit:
Well i wasn't able to save it with the same memStream so instead i did this.
memStream2 = New MemoryStream(pck.GetAsByteArray())
MailMsg.Attachments.Add(New Attachment(memStream2, "myFile2.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
And that worked as a charm. Hope is useful to anyone.

Export Crystal Report to PDF in a Loop only works with first

i'm trying to generate a report and export it to pdf in a loop, the report will receive a new parameter in each loop and prompt the client to download a PDF, in other words, the client may need to download 2 or 3 (or more) PDFs at the same time, the problem is that the prompt to accept the download only appears for the first pdf, dont know why. I can export to disk (server side) without any problems.
Code:
Sub PrintReport(ByVal Cod As Integer)
Dim CTableLogInfo As TableLogOnInfo
Dim ConnInfo As CrystalDecisions.Shared.ConnectionInfo = New ConnectionInfo()
ConnInfo.Type = ConnectionInfoType.SQL
ConnInfo.ServerName = ConfigurationManager.AppSettings("SQLSERVERNAME")
ConnInfo.DatabaseName = ConfigurationManager.AppSettings("SQLDBNAME")
ConnInfo.UserID = ConfigurationManager.AppSettings("SQLSERVERUSER")
ConnInfo.Password = ConfigurationManager.AppSettings("SQLSERVERPASSWORD")
ConnInfo.AllowCustomConnection = False
ConnInfo.IntegratedSecurity = False
For Each CTable As Table In CrystalReportSource1.ReportDocument.Database.Tables
CTable.LogOnInfo.ConnectionInfo = ConnInfo
CTableLogInfo = CTable.LogOnInfo
CTableLogInfo.ReportName = CrystalReportSource1.ReportDocument.Name
CTableLogInfo.TableName = CTable.Name
CTable.ApplyLogOnInfo(CTableLogInfo)
Next
Dim pField As ParameterField = CrystalReportSource1.ReportDocument.ParameterFields(0)
Dim val1 As ParameterDiscreteValue = New ParameterDiscreteValue
val1.Value = Cod
pField.CurrentValues.Clear()
pField.CurrentValues.Add(val1)
Dim PDFName As String = "PDF Nº " & Cod
CrystalReportSource1.ReportDocument.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Page.Response, True, PDFName)
End Sub
EDIT:
Tried to zip the reports with DotNetZip but i get an broken zip.
Can you tell me whats wrong? (Solved: code bellow is corrected now)
Response.ClearContent()
Response.ClearHeaders()
Response.ContentType = "application/zip"
Response.AppendHeader("content-disposition", "attachment; filename=AllPDFs.zip")
Using zipFile As New ZipFile()
For i = 0 To Cod.Length - 1
If Cod(i) > 0 Then
val1.Value = Cod(i)
pField.CurrentValues.Clear()
pField.CurrentValues.Add(val1)
val2.Value = Cod(i)
pField2.CurrentValues.Clear()
pField2.CurrentValues.Add(val2)
Dim PDFNameAs String = "PDF Nº " & Cod(i) & ".pdf"
Dim s As New System.IO.MemoryStream
s =CrystalReportSource1.ReportDocument.ExportToStream(ExportFormatType.PortableDocFormat)
zipFile.AddEntry(PDFName, s)
End If
Next
zipFile.Save(Response.OutputStream)
End Using
Response.Clear()
Probably the response ends after the first one, therefore there's no response to write to for the 2nd and 3rd attempts.
Instead, you can have the client download the reports via AJAX Request (move your report generation into an .ashx generic handler), or have the user click the button 3 times to initiate new requests.
Or zip the PDF's up until a single file and allow the client to download that.

asp.net openxml open docx, change content and stream to user

My code is below. I'm trying to open a Word document with Open XML and change certain text. The document must then be send to the client where they can save it on their PC or Open it. It send a document to the client but it is blank. When I save my InMemory document it says the file cannot be open it must contain at least one root element. I'm using Visual STudio 2010 Express. Please help me. What is wrong with my code?
Dim fileName As String = "directory on server\doc.docx"
Dim myDocument As WordprocessingDocument = WordprocessingDocument.Open(fileName, True)
Dim docText As String = Nothing
Dim sr As StreamReader = New StreamReader(myDocument.MainDocumentPart.GetStream)
docText = sr.ReadToEnd
sr.Close()
Dim regexText As Regex = New Regex("XXXCourtXXX")
docText = regexText.Replace(docText, "JOHANNESBURG")
Dim ms As New MemoryStream()
Dim sw As StreamWriter = New StreamWriter(ms)
sw.Write(docText)
myDocument.MainDocumentPart.FeedData(ms)
Dim mem = New MemoryStream()
myDocument.MainDocumentPart.GetStream().CopyTo(Response.OutputStream)
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Response.AppendHeader("Content-Disposition", "attachment;filename=Notice.docx")
mem.Position = 0
mem.CopyTo(Response.OutputStream)
Response.Flush()
Response.End()
You're dimming a new memory stream mem, writing nothing to it and then copying it to the output stream. Remove all lines referencing your mem variable.

Resources