Search code examples
vb.netvariablesdirectorypath

How determine path in vb net for a text file then modify some lines inside


I have to modify a text file than can be located either in c:\folder\test.txt or in c:\folder1\test.txt I tried this: If My.Computer.FileSystem.DirectoryExists("C:\Folder") and I can determine where the file is located.

Right now I have this line to modify the test.txt because I know is located on c:\folder

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    fileContents = My.Computer.FileSystem.ReadAllText("c:\folder\test.txt")
    fileContents = Replace(fileContents, "true", "false")

How can I do this automatically so when I open the application the path will change automatically based on where the test file is located then all the selections using buttons I have to do will be based on the actual path where test.txt is located. Basically I have buttons assigned to change different lines located in test.txt

Thank you.


Solution

  • Based on your comment,

    I have to modify a text file than can be located either in c:\folder\test.txt or in c:\folder1\test.txt

    it's either in one path or the other. Check for the path to the file when your application starts

    Private Const PATH_0 = "c:\folder\test.txt"
    Private Const PATH_1 = "c:\folder1\test.txt"
    Private pathToRead As String
    
    Private Sub SandboxForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        If File.Exists(PATH_0) Then
            pathToRead = PATH_0
        ElseIf File.Exists(PATH_1) Then
            pathToRead = PATH_1
        Else
            MessageBox.Show("File not found!")
        End If
    End Sub
    

    Later, you already know the path so just use it

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim fileContents = Replace(File.ReadAllText(pathToRead), "true", "false")
    End Sub