Search/Replace in VB.NET - vb.net

Been following the threads for sometime as a novice (more of a newbie) but am now starting to do more.
I can read how to open a text file but am having trouble understanding the .replace functionality (I get the syntax just can't get it to work).
Scenario:
Inputfile name = test_in.txt
replace {inputfile} with c:\temp\test1.txt
I'm using test.txt as a template for a scripting tool and need to replace various values within to a new file called test_2.txt.
I've got variables defining the input and output files without a problem, I just can't catch the syntax for opening the new file and replacing.

You really have not given us that much to go on. But a common mistake in using String.Replace is that it makes a copy of the source which needs to be saved to another variable or else it will go into the bit bucket. So in your case, something like this should work.
Dim Buffer As String 'buffer
Dim inputFile As String = "C:\temp\test.txt" 'template file
Dim outputFile As String = "C:\temp\test_2.txt" 'output file
Using tr As TextReader = File.OpenText(inputFile)
Buffer = tr.ReadToEnd
End Using
Buffer = Buffer.Replace("templateString", "Hello World")
File.WriteAllText(outputFile, Buffer)

Try something like this:
Dim sValuesToReplace() As String = New String() {"Value1", "Value2", "Value3"}
Dim sText As String = IO.File.ReadAllText(inputFilePath)
For Each elem As String In sValuesToReplace
sText = sText.Replace(elem, sNewValue)
Next
IO.File.WriteAllText(sOutputFilePath, sText)
It depends if you want to replace all values with only one value, or with different values for each. If you need different values you can use a Dictionary:
Dim sValuesToReplace As New Dictionary(Of String, String)()
sValuesToReplace.Add("oldValue1", "newValue1")
sValuesToReplace.Add("oldValue2", "newValue2")
'etc
And then loop throgh it with:
For Each oldElem As String In sValuesToReplace.Keys
sText = sText.Replace(oldElem, sValuesToReplace(oldElem))
Next

Related

Reading text from one file, to check other text file for matches

So I'm new to VB.NET, and I'm trying to read through 2 separate text files. File2 first & pulling a variable from it. I then want to take that variable, and check File1 to see if the string matches. Both files are relatively large, and I have to trim part of the string from the beginning, hence the multiple splits. So currently, this is what I have. But where I'm getting hung up is, how do I get it to check every line to see if it matches with the other file?
Public Function FileWriteTest()
Dim file1 = My.Computer.FileSystem.OpenTextFileReader(path)
Dim file2 = My.Computer.FileSystem.OpenTextFileReader(path)
Do Until file2.EndOfStream
Dim line = file2.ReadLine()
Dim noWhiteSpace As New String(line.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
Dim split1 = Split(noWhiteSpace, "=")
Dim splitStr = split1(0)
If splitStr.Contains(HowImSplittingText) Then
Dim parameter = Split(splitStr, "Module")
Dim finalParameter = parameter(1)
End If
'Here is where I'm not sure how to continue. I have trimmed the variable to where I would like to check with the other file.
'But i'm not sure how to continue from here.
Here are a couple of cleanup notes:
Get the lines of your first file by using IO.File.ReadAllLines (documentation)
Get the text of the second file by using IO.File.ReadAllText (documentation)
Use String.Replace (documentation) instead of Char.IsWhitespace, this is quicker and much more obvious as to what is going on
Use String.Split (documentation) instead of Split (because this is 2021 not 1994).
In terms of what you would do next, you would call String.IndexOf (documentation) on the second file's text, passing your variable value, to see if it returns a value greater than -1. If it does, then you know where at in the file the value exists.
Here is an example:
Dim file1() As String = IO.File.ReadAllLines("path to file 1")
Dim file2 As String = IO.File.ReadAllText("path to file 2")
For Each line In file1
Dim noWhiteSpace As String = line.Replace(" ", String.Empty)
Dim split1() As String = noWhiteSpace.Split("=")
If (splitStr.Length > 0) Then
Dim splitStr As String = split1(0)
If splitStr.Contains(HowImSplittingText) Then
Dim parameter() As String = splitStr.Split("Module")
If (parameter.Length > 0) Then
Dim finalParameter As String = parameter(0)
Dim index As Integer = file2.IndexOf(finalParameter)
If (index > -1) Then
' finalParameter is in file2
End If
End If
End If
End If
Next

VB.net How to remove quotes characters from a streamReader.readline.split()

I had built a project that read data from a report and it used to work fine but now for some reason the report puts every thing in to strings. So I want to modify my stream reader to remove or ignore the quotes as it reads the lines.
This is a snipet of the part that reads the lines.
Dim RawEntList As New List(Of Array)()
Dim newline() As String
Dim CurrentAccountName As String
Dim CurrentAccount As Account
Dim AccountNameExsists As Boolean
Dim NewAccount As Account
Dim NewEntry As Entrey
Dim WrongFileErrorTrigger As String
ListOfLoadedAccountNames.Clear()
'opens the file
Try
Dim sr As New IO.StreamReader(File1Loc)
Console.WriteLine("Loading full report please waite")
MsgBox("Loading full report may take a while.")
'While we have not finished reading the file
While (Not sr.EndOfStream)
'spliting eatch line up into an array
newline = sr.ReadLine.Split(","c)
'storring eatch array into a list
RawEntList.Add(newline)
End While
And then of course I iterate through the list to pull out information to populate objects like this:
For Each Entr In RawEntList
CurrentAccountName = Entr(36)
AccountNameExsists = False
For Each AccountName In ListOfLoadedAccountNames
If CurrentAccountName = AccountName Then
AccountNameExsists = True
End If
Next
You could just do
StringName.Replace(ControlChars.Quote, "")
or
StringName.Replace(Chr(34), "")
OR
streamReader.readline.split().Replace(Chr(34), "")
How about doing the replace before the split, after the readline? That should save iteration multiplication, or better yet (if possible), do a replace on the entire file (if the data is formatted in the way it can be done & you have enough memory) using the ReadAllText method of the File object, do your replace, then read the lines from memory to build your array (super fast!).
File.ReadAllText(path)

Can I compute the name of a variable in VB.net

I want to know if it is possible to compute the name of a variable in VB.net. I need to open a bunch of text files at runtime. The exact number will be variable. I wanted to do something along the lines of:
For j = 1 to Filecount
Dim Filename As String = "File"&j
Dim File & j As New System.IO.StreamWriter(Filename)
Next
When I tried this, VB.net said it didn't like it. Is this possible?
I think you would be better off using a dictionary, which would allow you to get back to the appropriate stream writer using the filename later:
Dim fileDictoinary As New Dictionary(Of String, System.IO.StreamWriter)
For j = 1 To Filecount
Dim Filename As String = "File" & j
fileDictoinary.Add(Filename, New System.IO.StreamWriter(Filename))
Next
Then at a later time you can access the streamwriter using the filename in the dictionary:
Dim file4StreamWriter = fileDictoinary("File4")
file4StreamWriter.Write(True)

How to read from a 2-line text file and output each line to 2 variables in vb.net

Hello in my program I need for a text file containing 2 lines to be read and each line's contents to be put into their own variable. the text file is called "account.txt" and is under the directory Documents. the code i have curently that sees if it exists is this:
If File.Exists(System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Account.txt")) Then
MsgBox("Account found and is being loaded!")
End If
I would like in that if statement for the file to be read and each line to be read and contents to be put into their own variable. Any help is greatly appreciated!
You could either use a collection like String() or List(Of String) or read them with File.ReadLines or File.ReadAllLines and assign index 0 to variable 1 and index 1 to variable 2:
Dim path = Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Account.txt")
If File.Exists(path) Then
Dim allLines = File.ReadAllLines(path)
Dim line1 As String = allLines(0) ' indices are zero based
Dim line2 As String = allLines(1)
End If
You can also use ElementAtOrDefault(1) instead of allLines(1) if you're not sure if the file contains two lines at all. It'l be Nothing if it contains less:
Dim line2 As String = allLines.ElementAtOrDefault(1) ' can be Nothing
If File.Exists(System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Account.txt")) Then
Dim accountReader As StreamReader = new StreamReader(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Account.txt")
Dim line1 As String = accountReader.ReadLine()
Dim line2 As String = accountReader.ReadLine()
reader.Close()
End If
This should work, have not tested it I usually work on C# so I tried to convert it to VB.Net I usually prefer to reader all lines into arrays and before assigned to it I do all necessary checks but this should get you started.
I seperated it like this since you mentioned that you want line contents into different variables.
Hope this helps you :)

Adding values to array

I am trying to run an event which will search through the different files in a given directory. The goal is to have it search for all files that begin with 'SP_', which are .sql files containing Stored Procedures. I would then like to add the full text of these Procedures to an array to be used later. This is causing an error when run, which I believe is because 'FullProcedureArray()', the string array I am trying to load does not have defined boundaries. When I declare it as 'FullProcedureArray(7)', or with some other value, it appears to run fine. But I don't want to have to hard-code a boundary for 'FullProcedureArray'; I would rather let it be defined by whatever the number of files in the folder is.
My question: Is there a way to declare 'FullProcedureArray' without having to give it an absolute value? I may just be missing something painfully obvious, but I haven't worked with this type of array much in the past. Thanks in advance for your help.
Dim AppDataLocation As String = "C:\Files\TestFiles\"
Dim ProcedureArray As String()
Dim ProcedureText As String
Dim FullProcedureArray() As String
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(AppDataLocation)
Dim fileSystemInfo As System.IO.FileSystemInfo
Dim i As Integer = 0
For Each fileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
If (fileSystemInfo.Name.Contains("SP_")) Then
ProcedureArray = System.IO.File.ReadAllLines(AppDataLocation & fileSystemInfo.Name)
ProcedureText = Join(ProcedureArray, "")
FullProcedureArray.SetValue(ProcedureText, i)
i = (i + 1)
End If
Next
An array by definition has a fixed upper bound. If you don't want a fixed upper bound, don't use an array. Use, for example, a List(Of String) instead:
Dim AppDataLocation As String = "C:\Files\TestFiles\"
Dim ProcedureList As New List(Of String)
Dim sourceDirectoryInfo As New System.IO.DirectoryInfo(AppDataLocation)
For Each fileSystemInfo As System.IO.FileSystemInfo In sourceDirectoryInfo.GetFileSystemInfos
If (fileSystemInfo.Name.Contains("SP_")) Then
Dim ProcedureText As String = _
System.IO.File.ReadAllText(AppDataLocation & fileSystemInfo.Name)
ProcedureList.Add(ProcedureText)
End If
Next
If, for some reason, you still need the result as an array afterwards, simply convert the list to an array:
Dim myArray() As String = ProcedureList.ToArray()
If you don't want to give a size to your array or want to change at runtime, you can use "Redim Preserve"
http://msdn.microsoft.com/en-us/library/w8k3cys2%28v=vs.71%29.aspx