问题描述
我在尝试读取由另一个进程打开的文本文件时遇到问题。 经过搜索之后,我发现了一些类似的问题,尽管在C#和VB.Net中似乎都指的是FileShare.ReadWrite是使此功能正常运行的关键,但我仍在为此苦苦挣扎。
Dim logFileStream As FileStream = New FileStream("C:\test.txt",FileMode.Open,FileAccess.Read,FileShare.ReadWrite)
Dim logFileReader As StreamReader = New StreamReader(logFileStream)
While Not logFileReader.EndOfStream
Dim line As String = logFileReader.ReadLine()
TextBox1.Text = line
End While
logFileReader.Close()
logFileStream.Close()
我的目标是只使用文件c:\ test.txt中的最后两行并将这些内容显示在Label中,但是我想我首先需要阅读并显示内容,然后才能开始查看只需提取最后两行。
解决方法
更新:
重新访问MS Docs之后,我重新排列了以下代码,现在看来可以将打开的文件读入TextBox
Dim strLogFilePath As String
Dim LogFileStream As FileStream
Dim LogFileReader As StreamReader
Dim strRowText As String
strLogFilePath = "C:\DSD\DSDPlus.srt"
LogFileStream = New FileStream(strLogFilePath,FileMode.Open,FileAccess.Read,FileShare.ReadWrite)
LogFileReader = New StreamReader(LogFileStream)
strRowText = LogFileReader.ReadToEnd()
TextBox1.Text = strRowText
LogFileReader.Close()
LogFileStream.Close()