将流下载到文件

时间:2019-11-18 09:39:20

标签: asp.net vb.net pdf stream

我有提供流的服务。该流应写入pdf文件。

我尝试了这种方法,但是没有用:

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

我也尝试了其他几种解决方案,但似乎都没有用。 我从没收到文件。

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

您可以在没有MemoryStream的Using块中读取缓冲区(如果那里有数据)(如下面的代码所示),并放置完整的绝对路径,如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

答案 1 :(得分:0)

这里是How do I save a stream to a file in C#的VB.NET版本

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