1

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?

2
  • Take a look [here][1] there is a good solution to do this [1]: stackoverflow.com/questions/15572061/… Commented Oct 22, 2014 at 9:29
  • 1
    would you be pleasant and write a real answer just but this into a answer so i can say it is the rigth answer... Commented Oct 22, 2014 at 9:40

2 Answers 2

1

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))
Sign up to request clarification or add additional context in comments.

4 Comments

Ok ill try it soon just gotta re install VB.NET, don't even ask me why i am stupid. ^^
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.
@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.
Thanks for the help really much but i found that a guy has a solution, found it on a other question.
0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.