我用的是VB2013 UPDATE4 EXPRESS。
作用是:在test.txt文件中,找出所有含“key”的行,并用 "hellokitty"代替,保存到此txt文件中。要求要用StreamReader与StreamWriter。
先上代码:
Imports System.IO
Imports System.Text
Public Class Form1
Private Sub btnTest_Click(sender As Object, e As EventArgs) Handles btnTest.Click
Dim mytextfile As String = "F:\test.txt"
Dim line As String = ""
Dim newline As String = ""
Dim myfilereader As New StreamReader(mytextfile, Encoding.ASCII)
Dim myfilewriter As New StreamWriter(mytextfile, False, Encoding.ASCII)
Do Until myfilereader.EndOfStream
line = myfilereader.ReadLine()
If line.Contains("key") Then
newline = line.Replace("key", "hellokitty")
myfilewriter.Write(newline)
End If
Loop
myfilereader.Close()
myfilewriter.Close()
End Sub
End Class
现在问题是,一旦调试,会发生以下错误:
其他信息: 文件“F:\test.txt”正由另一进程使用,因此该进程无法访问此文件。
请问:怎样修改代码,可以达成用StreamReader与StreamWriter替换字符的作用?
谢谢。
关于VB.NET:StreamReader与StreamWriter在替换txt文档中字符时该如何使用?
答案:2 悬赏:70
解决时间 2021-04-22 01:04
- 提问者网友:清茶柒夏
- 2021-04-21 01:37
最佳答案
- 二级知识专家网友:滚出爷的世界
- 2021-04-21 02:42
问题应该是出在StreamReader与StreamWriter不能同时对同一个文件进行操作。
可以边读边替换并保存到一个变量或数组中(感觉用StringBuilder最好),然后关闭StreamReader再打开StreamWriter进行保存。
可以边读边替换并保存到一个变量或数组中(感觉用StringBuilder最好),然后关闭StreamReader再打开StreamWriter进行保存。
全部回答
- 1楼网友:爱情是怎么炼成的
- 2021-04-21 04:08
不明白啊 = =!
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯