Find and replace text in a txt document using Visual Basic

后端 未结 4 1030
情书的邮戳
情书的邮戳 2020-12-21 00:27

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 th

4条回答
  •  太阳男子
    2020-12-21 00:51

    Dim fileReader As String = My.Computer.FileSystem.ReadAllText("C:\test.txt").Replace("foo", "bar")
    My.Computer.FileSystem.WriteAllText("C:\test2.txt", fileReader, False)
    

    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.

    Shorter version:

    My.Computer.FileSystem.WriteAllText("C:\test2.txt", My.Computer.FileSystem.ReadAllText("C:\test.txt").Replace("foo", "bar"), False)
    

提交回复
热议问题