2017-08-26 13 views
0

我试图在vb.net中创建一个程序,它的功能是当您打开一个文件时,将文件打开成十六进制代码,但问题是,如果我打开一个很大的文件,它通常会导致OutOfMemory异常。打开大文件并将其转换为十六进制导致OutOfMemory异常VB.NET

我试过一些东西,但没有任何工作。

 ToolStripLabel1.Text = "Status: Loading" 
    Cursor = Cursors.WaitCursor 

    If OpenFileDialog1.ShowDialog <> DialogResult.Cancel Then 
     Dim infoReader As IO.FileInfo 
     infoReader = My.Computer.FileSystem.GetFileInfo(OpenFileDialog1.FileName) 
     If Math.Truncate(infoReader.Length/1024/1024) > 15 Then 
      Dim x As MsgBoxResult 
      x = MsgBox("Opening files bigger than 15MB can cause the program to be unresponsive for long periods of time, crash or throw a OutOfMemory exception, depending on the size of the file." & vbCrLf & vbCrLf & "Are you sure you want to continue loading this file?", MsgBoxStyle.Exclamation + MsgBoxStyle.YesNo, "Warning - HEX EDITOR") 
      If x = MsgBoxResult.Yes Then 
        RichTextBox1.AppendText(String.Join(" ", File.ReadAllBytes(OpenFileDialog1.FileName).Select(Function(b) b.ToString("X2")))) 'This is where the exception would happen. 
       ToolStripLabel1.Text = "Status: Idle" 
      End If 
     Else 
      RichTextBox1.Text = String.Join(" ", IO.File.ReadAllBytes(OpenFileDialog1.FileName).Select(Function(b) b.ToString("X2"))) 
      ToolStripLabel1.Text = "Status: Idle" 
     End If 
    End If 
    RichTextBox2.Text = RichTextBox1.Text 
    NumericUpDown3.Maximum = RichTextBox1.Text.Length 
    NumericUpDown2.Maximum = RichTextBox1.Text.Length 
    NumericUpDown3.Value = RichTextBox1.Text.Length 
    Cursor = Cursors.Default 
    Label4.Text = "File Opened: " & OpenFileDialog1.FileName 

回答

0

不必加载在内存中的所有字节,然后试图执行的小2个字符的字符串的enourmous加入,你可以加载文件的数据块,将单个块为十六进制,并补充说,转换到RichTextBox的。所有异步/等待时尚

Async Sub FillWithHex(rtb As RichTextBox, name As String) 

    ' Arbitrary block size. Experiment with different sizes to 
    ' see the difference in loading times vs smooth scrolling in richtextbox   
    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 
End Sub 

而且从你的代码

If OpenFileDialog1.ShowDialog <> DialogResult.Cancel Then 
    FillWithHex(RichTextBox1, OpenFileDialog1.FileName) 
End Sub 
+0

感谢称呼它,我在想这样做,但我不知道如何做到这一点没有崩溃,或使错误。 – Coolvideos73

+0

我有一个问题,我无法保存,Invaild投射异常如果SaveFileDialog1.ShowDialog <> DialogResult.Cancel Then 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) End If – Coolvideos73

+0

与原始问题有什么共同点?请发布一个新问题。 – Steve

相关问题