在开头设置文件读指针

时间:2014-12-05 05:04:34

标签: vb.net streamreader

考虑下面的代码,其中对于key.txt中的每个条目,我将它添加到plain.txt中的每一行,并将其写入output.txt。

 Dim srKeyFile As New StreamReader("D:\Test\key.txt")

        Dim srOutFile As New StreamWriter("D:\TestBial\output.txt")
        Dim strKey, strPlain As String
        While srKeyFile.Peek() >= 0
            Dim srPlainFile As New StreamReader("D:\TestB\plain.txt")
            strKey = srKeyFile.ReadLine()
            Dim key As Integer = Integer.Parse(strKey)
            While srPlainFile.Peek() >= 0
                strPlain = srPlainFile.ReadLine()
                Dim plain As Integer = Integer.Parse(strPlain)
                srOutFile.WriteLine("" + (key + plain).ToString())
            End While
            srPlainFile.Close()
        End While
        srOutFile.Close()

上面我必须在外循环的每次迭代中打开和关闭内部文件。有一些方法我可以将指针定位到开头,每次我进入文件的内部循环plain.txt

1 个答案:

答案 0 :(得分:1)

您可以使用StreamReader的BaseStream.Seek来执行此操作,但您需要先调用DiscardBufferedData

    srPlainFile.DiscardBufferedData()
    srPlainFile.BaseStream.Seek(0, SeekOrigin.Begin)