16,722
社区成员




Private Sub Write_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Write.Click
Dim dataLength As Integer = 8 '每个元素的长度
Dim strPad As String = Chr(32).ToString() '填充时用的字符,这里是空格
Dim strSplit As String = Chr(9).ToString() '分隔每个元素的字符,这里是tab建
If File.Exists("C:\123.txt") Then
File.Delete("C:\123.txt")
End If
Dim sw As New StreamWriter("C:\123.txt", True)
Dim strLine As String = ""
strLine = LPad("x", strPad, dataLength) + strSplit + LPad("y", strPad, dataLength) + strSplit + LPad("z", strPad, dataLength)
sw.WriteLine(strLine)
strLine = LPad("3455", strPad, dataLength) + strSplit + LPad("34", strPad, dataLength) + strSplit + LPad("3212", strPad, dataLength)
sw.WriteLine(strLine)
strLine = LPad("56", strPad, dataLength) + strSplit + LPad("4", strPad, dataLength) + strSplit + LPad("2", strPad, dataLength)
sw.WriteLine(strLine)
sw.Flush()
sw.Close()
End Sub
Private Function LPad(ByVal strSrc As String, ByVal strPad As Char, ByVal intLength As Integer) As String
LPad = ""
If strSrc.Length > intLength Then
strSrc = strSrc.Substring(0, intLength)
End If
LPad = strSrc
While LPad.Length < intLength
LPad = strPad.ToString() + LPad
End While
End Function
Private Sub Read_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Read.Click
If Not File.Exists("C:\123.txt") Then
MsgBox("文件不存在")
End If
Dim sr As New StreamReader("C:\123.txt")
Dim strLine As String = ""
While Not sr.EndOfStream
'如果想取strline中的各个元素,可以用split(strSplit)来分割
strLine = sr.ReadLine().ToString()
MessageBox.Show(strLine)
End While
End Sub
'另外一种方式:
Dim sr As StreamReader
sr = File.OpenText("aa.txt")
Dim str As String = sr.ReadToEnd()
Dim lines As String() = str.Split(ControlChars.Lf)
For Each item As string In lines
Dim array As String() = item.Split("="C)
'按=号拆分字符串
Dim ctlName As String = array(0)
'文本框名称
Dim text As String = array(1)
'文本框内容
Next