locked
string replace does not work RRS feed

  • Question

  • User-258447744 posted

    Hi, I have following code snippet that is supposed to replace the existing text in a local text file but instead it's just appending the new values on top of the file and pushes the older text down. Here is the code:

    dim sr as streamreader = file.opentext(path)
    dim contents as string = sr.Readtoend()
    sr.close()
    Dim sw as streamwriter = file.Createtext(Path)
    sw.Write(contents.replace("old value1", "new value")
    sw.Write(contents.replace("old value2", string.empty)
    sw.close()

    Does any one know what do I need to change to make it replace existing text rather than append?

    Thanks

    Monday, May 10, 2010 8:27 PM

Answers

  • User-1360095595 posted

    You are writing the contents twice.  Maybe use:

    sw.Write(contents.Replace("old value1", "new value").Replace("old value2", string.empty))
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 10, 2010 9:14 PM

All replies

  • User-1360095595 posted

    You are writing the contents twice.  Maybe use:

    sw.Write(contents.Replace("old value1", "new value").Replace("old value2", string.empty))
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 10, 2010 9:14 PM
  • User-952121411 posted

    Yeah I ran across this several years ago myself.  Once easy way (because I can't recall where the code is where I dealt with this), is just to delete the file before writing to it, and then just creating it over again.  You already have modify permissions to the file obviously since you were changing the text, and this is a lot easier that trying to erase existing text line by line.  Try something like this:

            'Delete the existing file 1st:
            System.IO.File.Delete(Path)
            'Now re-create the file from scratch using the same path, but not 
            'needing to be concerned with replacing all of the text:
            Dim sw As StreamWriter = File.CreateText(Path)
            sw.Write("new value")
            sw.Close()


    'If you can not delete the file, you could use the method to overwrite the entire file 1st with an empty string:

    System.IO.File.WriteAllText(Path, String.Empty)

    Hope this helps! Smile

    Tuesday, May 11, 2010 4:50 PM
  • User-258447744 posted

    Thanks this code worked.

    Tuesday, May 11, 2010 7:25 PM