Hmm so i think the title explains enough. Hope someone has a answer. Thanks... Pretty much all I need to do is replace a string from a text file with another one. Any ideas?
-
Take a look [here][1] there is a good solution to do this [1]: stackoverflow.com/questions/15572061/…Gianluca Colombo– Gianluca Colombo2014-10-22 09:29:33 +00:00Commented Oct 22, 2014 at 9:29
-
1would you be pleasant and write a real answer just but this into a answer so i can say it is the rigth answer...Frosty Tosty– Frosty Tosty2014-10-22 09:40:32 +00:00Commented Oct 22, 2014 at 9:40
Add a comment
|
2 Answers
The easiest is to rewrite the whole file if it's not too large:
File.WriteAllText(path, File.ReadAllText(path).Replace(oldText, newText))
If you have to replace all words it's a little bit more difficult. Btw, what is a word by your definition at all? Here is one approach:
Dim newWords = From word In File.ReadAllText(path).Split()
Select If(word = oldWord, newWord, word)
File.WriteAllText(path, String.Join(" ", newWords))
4 Comments
Frosty Tosty
Ok ill try it soon just gotta re install VB.NET, don't even ask me why i am stupid. ^^
Frosty Tosty
hm just which vb are you using i am using vb 2010 and it does not work the first thing you typed at all. Also word means i got a script like this: { "id": "1.7.2", "time": "2014-04-02T12:00:00+02:00", "releaseTime": "2013-10-25T15:00:00+02:00", "type": "release", that is just a part of it. I need to replace 1.7.2 in the beginning.
Tim Schmelter
@FrostyTosty: i'm also using VS 2010. Maybe you have to add
Imports System.Linq for the second approach. According to your data: You should have mentioned that in your question since my approach would replace all occurences of 1.7.2. You might want to use a real csv-parser to initialze classes with meaningful properties like ID and Time instead.Frosty Tosty
Thanks for the help really much but i found that a guy has a solution, found it on a other question.
What you need is the code below... sourced on stackoverflow
Dim myStreamReaderL1 As System.IO.StreamReader
Dim myStream As System.IO.StreamWriter
Dim myStr As String
myStreamReaderL1 = System.IO.File.OpenText("C:\File.txt")
myStr = myStreamReaderL1.ReadToEnd()
myStreamReaderL1.Close()
myStr = myStr.Replace("OldString", "New String")
'Save myStr
myStream = System.IO.File.CreateText("C:\FileOut.txt")
myStream.WriteLine(myStr)
myStream.Close()