使用 Visual Basic 查找和替换 txt 文档中的文本 [英] Find and replace text in a txt document using Visual Basic
问题描述
我使用的是 Visual Basic 2008 Express Edition,我的目标是读取作为模板的整个 .txt 文件,并用一个新词替换一个词的所有出现,然后将这个新修改的文本保存在一个新的 .txt 中你按下一个命令按钮.有人可以给我一些建议吗?
Hi Im using Visual Basic 2008 Express Edition, my goal is to read an entire .txt file that works as a template and replace all ocurances of a word with a new one and save this new modified text in a new .txt when you press a command button. Can someone give me some tips?
推荐答案
Dim fileReader As String = My.Computer.FileSystem.ReadAllText("C:\test.txt").Replace("foo", "bar")
My.Computer.FileSystem.WriteAllText("C:\test2.txt", fileReader, False)
所以你应该使用 FileSystem 的 ReadAllText 方法,将路径作为参数传递并使用 Replace 方法来替换你想要替换的内容.对于更高级的替换用法,您可以使用正则表达式.您可以阅读有关 这里.
So you should use the ReadAllText method of the FileSystem, pass the path as parameter and use the Replace method to replace what you want to replace. For more advanced usages of replace you can use regular expressions. You can read about that here.
更短的版本:
My.Computer.FileSystem.WriteAllText("C:\test2.txt", My.Computer.FileSystem.ReadAllText("C:\test.txt").Replace("foo", "bar"), False)
这篇关于使用 Visual Basic 查找和替换 txt 文档中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!