2017-08-30 103 views
0

我想在vb.net中做一个程序,它的功能是当你打开一个文件时,它将文件打开成十六进制代码,但问题是,当它保存并尝试转换它恢复正常。它会导致:(无法强制类型'WhereSelectArrayIterator`2 [System.String,System.Byte]'类型的对象类型'System.Byte []'。)异常。无法投射类型为'WhereSelectArrayIterator`2 [System.String,System.Byte]'的对象以键入'System.Byte []'。 Vb.net

这里的打开和保存代码

打开文件代码:FillWithHex(RichTextBox1,OpenFileDialog1.FileName)

Async Sub FillWithHex(rtb As RichTextBox, name As String) 
    For Each ctl In Controls 
     ctl.Enabled = False 
    Next ctl 
    Dim buff(1000000) As Byte 

    Using fs = New FileStream(name, FileMode.Open) 
     Using br = New BinaryReader(fs) 
      While True 
       Dim text = String.Empty 
       buff = br.ReadBytes(1000000) 
       Await Task.Run(Sub() text = String.Join(" ", buff. 
          Select(Function(b) b.ToString("X2")))). 
          ConfigureAwait(True) 
       rtb.AppendText(text) 
       If buff.Length < 1000000 Then 
        Exit While 
       End If 
      End While 

     End Using 
    End Using 
    For Each ctl In Controls 
     ctl.Enabled = True 
    Next ctl 
    ToolStripLabel1.Text = "Status: Idle" 
End Sub 

这里是保存代码

 Try 
     Dim b As Byte() = RichTextBox1.Text.Split(" "c).Select(Function(n) Convert.ToByte(Convert.ToInt32(n, 16))) 
     My.Computer.FileSystem.WriteAllBytes(SaveFileDialog1.FileName, b, False) 
    Catch ex1 As Exception 
     Try 
      Dim b As Byte() = RichTextBox1.Text.Split(" "c).Select(Function(n) Convert.ToByte(Convert.ToInt32(n, 16))) 
      My.Computer.FileSystem.WriteAllBytes(OpenFileDialog1.FileName, b, False) 
     Catch ex As Exception 
      MsgBox("Exception caught : " + vbNewLine + vbNewLine + ex.ToString, MsgBoxStyle.Critical, "Exception Error") 
    End Try 
    End Try 

回答

0

扩展版从方法Enumerable你调用类型为IEnumerable(Of T)的对象的类,如Select方法,一般不返回数组。他们通常会返回一些实现IEnumerable(Of T)的类型。具体类型通常不重要。如果你需要一个数组,那么你需要在该对象上调用ToArrayToList将类似地创建List(Of T)。这意味着你需要这样的:

Dim b = RichTextBox1.Text. 
        Split(" "c). 
        Select(Function(n) Convert.ToByte(n, 16)). 
        ToArray() 

请注意,我已经删除了明确的类型声明,即As Byte(),并让类型推断。这使得整洁的代码,但你不必这样做,如果你认为具有显式类型是有帮助的。请注意,我也删除了无用的Convert.ToInt32呼叫。

+0

然而,无论何时我尝试保存更大的文件,它都会导致出现OutOfMemory异常 – Coolvideos73

+0

您需要按块处理数据,但我建议您在新问题中特别提出相关问题。 – jmcilhinney

相关问题