Open a file - replace 1 word - close a file

Posted on 2011-05-10
Last Modified: 2012-05-11
In my under - sized brain this code should work.

 If File.Exists("C:\KeyPatroller\SQL\CorporateRemote.sql") Then

            fStream = New FileStream("C:\KeyPatroller\SQL\CorporateRemote.sql", FileMode.Open, FileAccess.ReadWrite)

            sReader = New StreamReader(fStream)

            sReader.ReadToEnd.Replace("keypatrollerremote", "Bob")


        End If
Question by:MBoy
    1 Comment
    LVL 85

    Accepted Solution

    This line:

        sReader.ReadToEnd.Replace("keypatrollerremote", "Bob")

    Creates a string with the word replaced...but that string is not "linked" to your file at all.  The string is simply garbage collected when the sub/function exits.

    You need to store that modified string and then OVERWRITE the old file:
    Dim FileName As String = "C:\KeyPatroller\SQL\CorporateRemote.sql"
            If File.Exists(FileName) Then
                Dim contents As String = My.Computer.FileSystem.ReadAllText(FileName)
                contents = contents.Replace("keypatrollerremote", "Bob")
                My.Computer.FileSystem.WriteAllText(FileName, contents, False)
            End If

    Open in new window


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Do You Know the 4 Main Threat Actor Types?

    Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

    Suggested Solutions

    Here we come across an interesting topic of coding guidelines while designing automation test scripts. The scope of this article will not be limited to QTP but to an overall extent of using VB Scripting for automation projects. Introduction Now…
    Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
    An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
    In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    18 Experts available now in Live!

    Get 1:1 Help Now