2014-10-27 49 views
1

我之前对此代码非常感谢,但是我碰到了一个绊脚石,而且我不确定正确的路要走。我有下面的代码找到并替换超过120k的查找和替换。问题是文本文件很容易超过5个日志文件,所以我得到一个内存问题,这并不意外。那么,如果可能的话,我是否会将数据加载到块中?替换内存问题VB.net


Private Sub CmdBtnTestReplace_Click(sender As System.Object, e As System.EventArgs) Handles CmdBtnTestReplace.Click 
    Dim fName As String = "c:\backup\logs\master.txt" 
    Dim wrtFile As String = "c:\backup\logs\masterUserFormatted.txt" 
    Dim strRead As New System.IO.StreamReader(fName) 
    Dim strWrite As New System.IO.StreamWriter(wrtFile) 
    Dim s As String 


    s = strRead.ReadToEnd() 

    'runs through over 120k of find and replaces 
    For Each row As DataGridViewRow In DataGridView1.Rows 
     If Not row.IsNewRow Then 

      Dim Find1 As String = row.Cells(0).Value.ToString 
      Dim Replace1 As String = row.Cells(1).Value.ToString 

      Cursor.Current = Cursors.WaitCursor 

      'replace using string from 1st column and replaces with string from 2nd column. 
      s = s.Replace(Find1, Replace1) 

     End If 

    Next 

    strWrite.Write(s) 
    strRead.Close() 
    strWrite.Close() 

    Cursor.Current = Cursors.Default 
    MessageBox.Show("Finished Replacing") 

End Sub 

回答

1

如果输入的文件是一个简单的多行文本文件,如果没有专用线是太大,加载到内存中一次,并搜索字符串是永远不会跨越多个行,然后一次只读一行将是最简单的解决方案。例如:

Dim fName As String = "c:\backup\logs\master.txt" 
Dim wrtFile As String = "c:\backup\logs\masterUserFormatted.txt" 
Dim strRead As New System.IO.StreamReader(fName) 
Dim strWrite As New System.IO.StreamWriter(wrtFile) 
Cursor.Current = Cursors.WaitCursor 
While True 
    Dim line As String = strRead.ReadLine() 
    If line IsNot Nothing Then 
     For Each row As DataGridViewRow In DataGridView1.Rows 
      If Not row.IsNewRow Then 
       Dim Find1 As String = row.Cells(0).Value.ToString 
       Dim Replace1 As String = row.Cells(1).Value.ToString 
       line = line.Replace(Find1, Replace1) 
      End If 
     Next 
     strWrite.WriteLine(line) 
    Else 
     Exit While 
    End If 
End While 
strRead.Close() 
strWrite.Close() 
Cursor.Current = Cursors.Default 
MessageBox.Show("Finished Replacing") 

值得一提的是,StreamReaderStreamReader实施IDisposable。因此,最好将它们放在Using区块中,而不是自己明确地调用Close

+0

嗨史蒂夫,非常感谢您的回复,我已经更新和测试,但它似乎并没有通过发现和替换的琐事超过100K。亲切的问候, – vbvirg20 2014-10-27 17:22:22

+0

@ vbvirg20我已经更新了我的答案,包括一个更完整的例子。让我知道你是否仍然有麻烦。 – 2014-10-27 17:44:11

+0

Steven你是一个明星,感谢你的帮助和你的解释,显然我需要在我的循环上做更多的工作。非常感谢,VBvirg – vbvirg20 2014-10-29 08:43:37