VB.NET编程读取txt文本文档中的数据,并把数据保存为数组,代码如下:
专注于为中小企业提供成都网站建设、成都网站设计服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业花溪免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上千企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
'写配件文件
Private Sub saveIni(ByVal filePath As String, ByVal str As String)
Dim sw As StreamWriter = New StreamWriter(filePath, True) 'true是指以追加的方式打开指定文件
sw.WriteLine(str)
sw.Flush()
sw.Close()
sw = Nothing
End Sub
'读配件文件
Private Function readIni(ByVal filePath As String)
Dim iniDt As New DataTable
iniDt.Columns.Add("text")
iniDt.Columns.Add("value")
Try
Dim sr As StreamReader = New StreamReader(filePath, System.Text.Encoding.Default)
Dim line As String = ""
While Not sr.EndOfStream
Dim str = sr.ReadLine()'读取当前行
iniDt.Rows.Add(New String() {
str(0),
str(1)
})
End While
sr.Close()
sr = Nothing
Catch ex As Exception
End Try
Return iniDt
End Function
已测试,代码如下:
Imports System.IO '引入文本操作
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim txt As String = Me.getTxt
SaveTxt(txt)
End Sub
'取得存储的文本
Private Function getTxt() As String
Dim x(0 To 10) As Integer
For i As Integer = 0 To x.Length - 1
x(i) = CInt(100 * Rnd())
Next
Dim str As String = ""
For j As Integer = 0 To x.Length - 1
str += x(j).ToString vbCrLf
Next
Return str
End Function
'存储文本
Private Sub SaveTxt(ByVal v As String)
Dim fp As String = GetSavePath()
If String.IsNullOrEmpty(fp) = False Then
'StreamWriter
Dim Swriter As New StreamWriter(fp, False) '覆盖或新建
Swriter.WriteLine(v)
Swriter.Close()
End If
End Sub
'取得存储路径
Private WithEvents sd As New SaveFileDialog
Private Function GetSavePath() As String
sd.FileName = ""
sd.AddExtension = True
sd.DefaultExt = "txt"
sd.Filter = "TXT文件(*.txt)|*.txt"
sd.ShowDialog()
Return sd.FileName
End Function
End Class
测试截图如下。
代码及注释如下:
Dim aa$, s, ss'定义变量
Private Sub Form_Load()
Open "c:\temp.txt" For Input As #1'打开txt文件
aa = StrConv(InputB(LOF(1), 1), vbUnicode)'将文本读入aa中
Close #1'关闭文件
End Sub
Private Sub Command1_Click()
s = Split(aa, vbNewLine)'将文本分离出来并放入数组s中
For i = 0 To UBound(s)'i从0到S的最大元素数循环
If s(i) "" Then'如果数组部位空
ss = Split(s(i), "=")'择将数组按照=分离,并放入数组ss
Print Val(ss(1))‘显示数值化的数组ss第一个元素
End If
Next i
End Sub
软糖来告诉你吧。
VB.net中读写文件主要使用System.IO命名空间。
① 使用 File.ReadAllText 读取
Dim s As String = System.IO.File.ReadAllText("C:\a.txt")
② 使用 StreamReader 读取,注意编码格式和写入的编码保持一致。
Dim sr As StreamReader = New StreamReader("C:\a.txt", System.Text.Encoding.UTF8)
Dim s As String = sr.ReadToEnd()
sr.Close()
③ 使用 File.WriteAllText 写入,会覆盖同名的文件。
Dim 要写的内容 As String = ""
File.WriteAllText(文件路径, 要写的内容, System.Text.Encoding.UTF8)
④ 使用 StreamWriter 写入。
Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter("C:\a.txt", False, System.Text.Encoding.UTF8)
sw.WriteLine(TextTB.Text)
sw.Close()
⑤ 使用 StreamWriter 追加写入。
将上面代码的第二个参数False改为True。
◆ 满意请采纳,谢谢 ◆