簡體   English   中英

嘗試從字節流中打開docx文件-文件損壞錯誤

[英]Trying to open a docx file from a bytestream - file corruption error

從保存的字節流中打開docx文件時,我們始終收到文件損壞的錯誤消息,可以使用其他文件類型就可以了

下面是示例表格中的代碼,該代碼可以解決該問題

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    'Objective is to be able to copy a file to a bytestream then create a new document from that stream  and then opne it.
    'This replicates the behaviour of our primary application where it stores and retrieves the stream from a database
    'With docx files we consistently experience some sort of corruption in the write of the original file
    'When selecting .doc or other format files we do not encounter the same problem

    'use selected file
    Dim _o1 As String = TextBox1.Text
    'get its bytestream
    Dim fs As New FileStream(_o1, FileMode.Open, FileAccess.Read)
    Dim byteStream(Convert.ToInt32(fs.Length)) As Byte
    fs.Read(byteStream, 0, Convert.ToInt32(fs.Length))

    'create a new file and use the bytestream to create it and save to disk
    Dim _o As String = "C:\" & Now.Ticks & getNewFileName()

    Dim fs1 As New FileStream(_o, FileMode.OpenOrCreate, FileAccess.Write)
    Using bw As New BinaryWriter(fs1)
        bw.Write(byteStream)
        bw.Flush()
    End Using

    'open the new document
    System.Diagnostics.Process.Start(_o)
    Application.DoEvents()
End Sub
Private Function getNewFileName() As String
    Dim fi As New FileInfo(TextBox1.Text)

    Return Now.Ticks.ToString & fi.Name
End Function
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    OpenFileDialog1.InitialDirectory = "c:\"
    OpenFileDialog1.FilterIndex = 2
    OpenFileDialog1.RestoreDirectory = True
    OpenFileDialog1.Filter = "docx files |*.docx"

    If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
        TextBox1.Text = OpenFileDialog1.FileName

    End If

End Sub

原諒我,但這是一些混亂的代碼。

Dim _o As String = "C:\" & Now.Ticks & getNewFileName()

會變成...

Dim _o As String = "C:\" & Now.Ticks & Now.Ticks.ToString & fi.Name

示例結果“ C:\\”“ 634015010433498951”“ 634015010433498951”“ FileName.txt”可能不是您所期望的,除非您打算減去兩個滴答計數以確定填充FileInfo所花費的時間。

您的FileStream損壞可能是編碼問題,可能是一個文件長度問題,甚至是深路徑中的長文件名也可能是問題。 代替使用FileStream,此代碼應該可以正常工作:

Dim sourceFile As String = TextBox1.text
Dim fi As New System.IO.FileInfo(sourceFile)
Dim destFile = "C:\" & Now.Ticks & fi.Name
fi.CopyTo(destFile)
'open the new document   
System.Diagnostics.Process.Start(destFile)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM