求vb.net删除文本文件中的第一行和最后一行
DimnewfileAsNewList(OfString)ForEachlineAsStringInSystem.IO.File.ReadAllLines("TextFi...
Dim newfile As New List(Of String)
For Each line As String In System.IO.File.ReadAllLines("TextFile1.txt")
If Not line.StartsWith("3") Then newfile.Add(line)
Next
System.IO.File.WriteAllLines("TextFile1.txt", newfile)
这段代码提示System.IO.File.WriteAllLines("TextFile1.txt", newfile)中的newfile无法转换string的1维数组
还请大神指教详细的代码,谢谢
环境Microsoft Visual 2005下 展开
For Each line As String In System.IO.File.ReadAllLines("TextFile1.txt")
If Not line.StartsWith("3") Then newfile.Add(line)
Next
System.IO.File.WriteAllLines("TextFile1.txt", newfile)
这段代码提示System.IO.File.WriteAllLines("TextFile1.txt", newfile)中的newfile无法转换string的1维数组
还请大神指教详细的代码,谢谢
环境Microsoft Visual 2005下 展开
1个回答
展开全部
方法先按行读取,并进行筛选,然后再写回到文件。
一行一行读取文本文件的例子:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim r As New StreamReader(Application.StartupPath & "\ABC.txt", System.Text.Encoding.Default) '用StreamReader打开文本文件
Dim s As String
TextBox1.Text = ""
Do While r.Peek > -1 '是否到文件尾
s = r.ReadLine '从打开的文件中读取一行内容
TextBox1.Text = TextBox1.Text & s & vbCrLf '添加到文本框TextBox1.Text的后面并回车
Loop
r.Close() '关闭对象
End Sub
End Class
写文本文件的例子:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'创建FileStream对象
Dim w As New FileStream(Application.StartupPath & "\ABC.txt", FileMode.Create)
'创建BinaryWriter对象
Dim b_Write As BinaryWriter = New BinaryWriter(w, System.Text.Encoding.UTF8)
b_Write.Write(TextBox1.Text)
b_Write.Close()
w.Close()
End Sub
End Class
一行一行读取文本文件的例子:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim r As New StreamReader(Application.StartupPath & "\ABC.txt", System.Text.Encoding.Default) '用StreamReader打开文本文件
Dim s As String
TextBox1.Text = ""
Do While r.Peek > -1 '是否到文件尾
s = r.ReadLine '从打开的文件中读取一行内容
TextBox1.Text = TextBox1.Text & s & vbCrLf '添加到文本框TextBox1.Text的后面并回车
Loop
r.Close() '关闭对象
End Sub
End Class
写文本文件的例子:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'创建FileStream对象
Dim w As New FileStream(Application.StartupPath & "\ABC.txt", FileMode.Create)
'创建BinaryWriter对象
Dim b_Write As BinaryWriter = New BinaryWriter(w, System.Text.Encoding.UTF8)
b_Write.Write(TextBox1.Text)
b_Write.Close()
w.Close()
End Sub
End Class
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |