2010-02-10 34 views
2

我们始终从保存的字节流打开的docx文件时得到一个文件损坏的错误消息,埃夫里,其它类型文件的工作方式确定试图从一个字节流打开的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 
+0

不应该关闭fs1和fs吗? – 2010-02-11 21:36:02

回答

1

原谅我,但那是一些乱七八糟的代码。

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) 
相关问题