对与文本文件这个大家都知道的,在VB.NET编程中,怎么样把数据保存为VB.NET TXT文件,现在我们就看下面的代码解析。
VB.NET TXT文件代码:
Private Sub Command1_Click()
'写文件示例
Dim strFileName As String '文件名
Dim lngHandle As Long '句柄
Dim strWrite As String '要写入的文本内容
strFileName = App.Path & "\a.txt"
''''''''App.Path & "\a.txt"相对路径
''"c:\w.txt"绝对路径
lngHandle = FreeFile() '取得句柄
'准备要写入的内容
strWrite = Text1.Text '或者 strWrite = "这些文字将被写入文件。"
'For后面的参数表示以何种方式打开文件,Input是读取,Output是覆盖写入,Append是追加写入
''''''append是每次在文件末尾写入,不删除其它已经存在的文件.如果换成output则删除其它文件后再写入
''''''print#1,text1.text ''''''如果print换成write则写进txt中后自动加双引号
Open strFileName For Output As lngHandle '打开文件
Print #lngHandle, strWrite '写入文本
Close lngHandle '关闭文件
End Sub
Private Sub Command2_Click()
'读文件示例
Dim strFileName As String '文件名
Dim lngHandle As Long '文件句柄
Dim strAll As String '所读取的文本文件的所有内容
Dim strLine As String '在循环中存放每行的内容
strFileName = App.Path & "\a.txt"
'获得文件的句柄
lngHandle = FreeFile()
'For后面的参数表示以何种方式打开文件,Input是读取,Output是覆盖写入,Append是追加写入
Open strFileName For Input As lngHandle
'循环直到文件尾
Do While Not EOF(lngHandle)
'每次读取一行存放在strLine变量中
Line Input #lngHandle, strLine
'每次读取都把所读到的内容连接到strAll变量,由于Line Input去掉了换行符,所以这里补上
strAllstrAll = strAll & strLine & vbCrLf
Loop
'显示得到的全部分内容
MsgBox strAll
End Sub
Private Sub Command1_Click()
Open App.Path & "\a.txt" For Output As #1
Print #1, Text1.Text '这里可以是数据本身也可以是目标控件的属性
Close #1 '关闭打开的文件
End Sub
'For后面的参数表示以何种方式打开文件,Input是读取,Output是覆盖写入,Append是追加写入
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
append是每次在文件末尾写入,不删除其它已经存在的文件.如果换成output则删除其它文件后再写入 print#1,text1.text 如果print换成write则写进txt中后自动加双引号,以上就是数据保存为VB.NET TXT文件的代码。
【编辑推荐】