Vb.net File.ReadAllLines 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30756156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vb.net File.ReadAllLines Method
提问by LukmanH
I've created an application with timer that is to change the text of a label based on the contents of my file.
我创建了一个带有计时器的应用程序,它可以根据我的文件内容更改标签的文本。
My text file:
我的文本文件:
00:00:05 "Some Text"
00:00:10 "Some Text"
00:00:25 "Some Text"
Just like a subtitle file, my form will change the label text at each of the timestamps.
就像字幕文件一样,我的表单将更改每个时间戳的标签文本。
I use this code to read the text file:
我使用此代码读取文本文件:
Dim Lines = File.ReadAllLines(MyFile)
Dim line1() As String = Lines.ElementAtOrDefault(0).Split
Dim line2() As String = Lines.ElementAtOrDefault(1).Split
Dim line3() As String = Lines.ElementAtOrDefault(2).Split
But it doesn't work on if the file has more than 3 lines.
但如果文件超过 3 行,它就不起作用。
What the solution for this?
对此有什么解决方案?
回答by LInsoDeTeh
You should use a loop instead of hard-coding 0, 1, and 2. To stay with your variable names:
您应该使用循环而不是硬编码 0、1 和 2。要保留变量名称:
Dim Lines = File.ReadAllLines(MyFile)
For Each line In Lines
Dim splittedLine() As String = line.Split
'whatever you do with the splitted line
Next
回答by Enigmativity
I would go about doing it like this:
我会这样做:
Dim now = DateTime.Now
Dim data = _
( _
From line in File.ReadLines(MyFile) _
Let timestamp = now.Add(TimeSpan.Parse(line.Substring(0, 8))) _
Let text = String.Join(" ", line.Split().Skip(1)) _
Select New With { .TimeStamp = timestamp, .Text = text } _
).ToArray()
From my sample data I then get these results:
从我的示例数据中,我得到了这些结果:


As you can see, the array contains the actual time to display the text and the text itself. It should be fairly easy now to use the timer to compare the current time with the next time stamp and move an index to keep track of the current line to display.
如您所见,该数组包含显示文本的实际时间和文本本身。现在使用计时器将当前时间与下一个时间戳进行比较并移动索引以跟踪要显示的当前行应该相当容易。

