How to remove a line of text from a txt file - vb.net

I have a txt file with a list of items in it, each item has its own line. I have this loop that looped through each line of the text file. But how do I delete the line once I have found it?
Dim item As String = lbxPrimary.SelectedItem
For Each Line As String In File.ReadAllLines(storepath & "Primary Items.txt")
If Line.Contains(item) = True Then
'Delete line here
Exit For
End If
Next

You can convert content() into a List(Of String) to use its method List(Of T).Remove to remove the first occurrence matching the specified argument.
Dim content() As String = File.ReadAllLines(storepath & "Primary Items.txt")
Dim list As List(Of String) = content.ToList
list.Remove(lbxPrimary.SelectedItem)
File.WriteAllLines(storepath & "Primary Items.txt", list)

Related

How can I reasd text from text file while there are multiple line and generate a string so I can use it as sqlconnection string?

I have a config file which contain multiple lines.
DataBaseType =1
ServerName=LAPTOP-XXXX
Database=mydatabase
Connection Timeout=3000
User ID=sa
Password=sasa
ServerIp=xxxx:8083
ServiceType=http://
Backup Driver=D:\
Backup Folder=SWBACKUP
Database Restore=D:\
Now I want to generate a string which will be a sqlconnection string by reading,splitting and joining texts. it should be
"Data Source=LAPTOP-XXXX;Initial Catalog=mydatabase;User ID=sa;Password=sasa"
I am able to read text using streamreader , but I am not able to split and join those texts.
You can create a method that converts your config file to a Dictionary(Of String, String) and then get the values as needed.
Take a look at this example:
Private Function ReadConfigFile(path As String) As Dictionary(Of String, String)
If (String.IsNullOrWhiteSpace(path)) Then
Throw New ArgumentNullException("path")
End If
If (Not IO.File.Exists(path)) Then
Throw New ArgumentException("The file does not exist.")
End If
Dim config = New Dictionary(Of String, String)
Dim lines = IO.File.ReadAllLines(path)
For Each line In lines
Dim separator = line.IndexOf("=")
If (separator < 0 OrElse separator = line.Length - 1) Then
Throw New Exception("The following line is not in a valid format: " & line)
End If
Dim key = line.Substring(0, separator)
Dim value = line.Substring(separator + 1)
config.Add(key, value)
Next
Return config
End Function
Example: Live Demo
What this Function does is:
Make sure that a path was given
Make sure that the file exists as the given path
Loop over each line
Make sure that the line is in the correct format (key=value)
Append the Key/Value to the Dictionary
you can use readline method, then make something as follow for database line:
Dim reader As New StreamReader(filetoimport.Txt, Encoding.Default)
Dim strLine As String
Do
' Use ReadLine to read from your file line by line
strLine = reader.ReadLine
Dim retString As String
'to get the string from position 0 length 8
retString = strLine .Substring(0, 8)
'check if match
if retString ="Database" Then
Dim valueString As String
valueString = strLine .Substring(9, strLine.length)
...
Loop Until strLine Is Nothing

Get a specific value from the line in brackets (Visual Studio 2019)

I would like to ask for your help regarding my problem. I want to create a module for my program where it would read .txt file, find a specific value and insert it to the text box.
As an example I have a text file called system.txt which contains single line text. The text is something like this:
[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]
What i want to do is to get only the last name value "xxx_xxx" which every time can be different and insert it to my form's text box
Im totally new in programming, was looking for the other examples but couldnt find anything what would fit exactly to my situation.
Here is what i could write so far but i dont have any idea if there is any logic in my code:
Dim field As New List(Of String)
Private Sub readcrnFile()
For Each line In File.ReadAllLines(C:\test\test_1\db\update\network\system.txt)
For i = 1 To 3
If line.Contains("Last Name=" & i) Then
field.Add(line.Substring(line.IndexOf("=") + 2))
End If
Next
Next
End Sub
Im
You can get this down to a function with a single line of code:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Return File.ReadLines(fileName).Where(Function(line) RegEx.IsMatch(line, "[[[]Last Name=(?<LastName>[^]]+)]").Select(Function(line) RegEx.Match(line, exp).Groups("LastName").Value)
End Function
But for readability/maintainability and to avoid repeating the expression evaluation on each line I'd spread it out a bit:
Private Function readcrnFile(fileName As String) As IEnumerable(Of String)
Dim exp As New RegEx("[[[]Last Name=(?<LastName>[^]]+)]")
Return File.ReadLines(fileName).
Select(Function(line) exp.Match(line)).
Where(Function(m) m.Success).
Select(Function(m) m.Groups("LastName").Value)
End Function
See a simple example of the expression here:
https://dotnetfiddle.net/gJf3su
Dim strval As String = " [Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim strline() As String = strval.Split(New String() {"[", "]"}, StringSplitOptions.RemoveEmptyEntries) _
.Where(Function(s) Not String.IsNullOrWhiteSpace(s)) _
.ToArray()
Dim lastnameArray() = strline(1).Split("=")
Dim lastname = lastnameArray(1).ToString()
Using your sample data...
I read the file and trim off the first and last bracket symbol. The small c following the the 2 strings tell the compiler that this is a Char. The braces enclosed an array of Char which is what the Trim method expects.
Next we split the file text into an array of strings with the .Split method. We need to use the overload that accepts a String. Although the docs show Split(String, StringSplitOptions), I could only get it to work with a string array with a single element. Split(String(), StringSplitOptions)
Then I looped through the string array called splits, checking for and element that starts with "Last Name=". As soon as we find it we return a substring that starts at position 10 (starts at zero).
If no match is found, an empty string is returned.
Private Function readcrnFile() As String
Dim LineInput = File.ReadAllText("system.txt").Trim({"["c, "]"c})
Dim splits = LineInput.Split({"]["}, StringSplitOptions.None)
For Each s In splits
If s.StartsWith("Last Name=") Then
Return s.Substring(10)
End If
Next
Return ""
End Function
Usage...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = readcrnFile()
End Sub
You can easily split that line in an array of strings using as separators the [ and ] brackets and removing any empty string from the result.
Dim input As String = "[Name=John][Last Name=xxx_xxx][Address=xxxx][Age=22][Phone Number=8454845]"
Dim parts = input.Split(New Char() {"["c, "]"c}, StringSplitOptions.RemoveEmptyEntries)
At this point you have an array of strings and you can loop over it to find the entry that starts with the last name key, when you find it you can split at the = character and get the second element of the array
For Each p As String In parts
If p.StartsWith("Last Name") Then
Dim data = p.Split("="c)
field.Add(data(1))
Exit For
End If
Next
Of course, if you are sure that the second entry in each line is the Last Name entry then you can remove the loop and go directly for the entry
Dim data = parts(1).Split("="c)
A more sophisticated way to remove the for each loop with a single line is using some of the IEnumerable extensions available in the Linq namespace.
So, for example, the loop above could be replaced with
field.Add((parts.FirstOrDefault(Function(x) x.StartsWith("Last Name"))).Split("="c)(1))
As you can see, it is a lot more obscure and probably not a good way to do it anyway because there is no check on the eventuality that if the Last Name key is missing in the input string
You should first know the difference between ReadAllLines() and ReadLines().
Then, here's an example using only two simple string manipulation functions, String.IndexOf() and String.Substring():
Sub Main(args As String())
Dim entryMarker As String = "[Last Name="
Dim closingMarker As String = "]"
Dim FileName As String = "C:\test\test_1\db\update\network\system.txt"
Dim value As String = readcrnFile(entryMarker, closingMarker, FileName)
If Not IsNothing(value) Then
Console.WriteLine("value = " & value)
Else
Console.WriteLine("Entry not found")
End If
Console.Write("Press Enter to Quit...")
Console.ReadKey()
End Sub
Private Function readcrnFile(ByVal entry As String, ByVal closingMarker As String, ByVal fileName As String) As String
Dim entryIndex As Integer
Dim closingIndex As Integer
For Each line In File.ReadLines(fileName)
entryIndex = line.IndexOf(entry) ' see if the marker is in our line
If entryIndex <> -1 Then
closingIndex = line.IndexOf(closingMarker, entryIndex + entry.Length) ' find first "]" AFTER our entry marker
If closingIndex <> -1 Then
' calculate the starting position and length of the value after the entry marker
Dim startAt As Integer = entryIndex + entry.Length
Dim length As Integer = closingIndex - startAt
Return line.Substring(startAt, length)
End If
End If
Next
Return Nothing
End Function

vb.net edit a file based on criteria and save it

I have a file that has dates and results of tests, written line by line. I would like to edit the file such that any line that does not have today's date is deleted and then the file is saved (with the unwanted lines deleted). Help will be greatly appreciated.
Dim rawlines() As String
Dim outputlines As New List(Of String)
rawlines = File.ReadAllLines("C:\users\user10\rslts.csv")
For Each line As String In rawlines
If line.Contains(today()) = True Then
outputlines.Add(line)
End If
Next
Read Lines:
Dim rawlines() As String
Dim outputlines As New List(Of String)
rawlines = File.ReadAllLines("C:\users\user10\rslts.csv")
For Each line As String In rawlines
If line.Contains(today()) = True Then
outputlines.Add(line)
End If
Next
Write lines to new file:
Dim MyFile As StreamWriter
File.Create("c:\test\TheResults.csv").Close()
MyFile = File.AppendText("c:\test\TheResults.csv")
For Each Line As String In outputlines
MyFile.WriteLine(Line)
Next
MyFile.Close()

Remove a line from text file vb.net

I'm using vb.net windows form app. I want to remove line from list of lines.
So if the line in textbox exists on that list, to be remove from list, and file to be saved.
I have a file list.txt with list of numbers :
123-123
321-231
312-132
If I write in textbox : 321-231 and if list.txt contains that line then remove it.
so result need to be :
123-123
321-132
I was trying with this code :
Dim lines() As String
Dim outputlines As New List(Of String)
Dim searchString As String = Textbox1.Text
lines = IO.File.ReadAllLines("D:\list.txt")
For Each line As String In lines
If line.Contains(searchString) = True Then
line = "" 'Remove that line and save text file (here is my problem I think )
Exit For
End If
Next
Put each string as you process it in the outputlines list, unless it matches the value typed in, like this:
Dim lines() As String
Dim outputlines As New List(Of String)
Dim searchString As String = Textbox1.Text
lines = IO.File.ReadAllLines("D:\list.txt")
For Each line As String In lines
If line.Contains(searchString) = False Then
outputlines.Add(line)
End If
Next
Now outputlines matches every line that did not match what was typed in by the user and you can write the contents of the outputlines list to file.

vb.net modify column in CSV file

I have a CSV file with many rows in which I need to update/replace column four's value using VB.NET. There are no headers on the columns so the loop can start on row one.
infile.csv
"value1","value2","value3","value4"
After much googling, there are lots of examples on how to read and write CSV files, but none quite what is needed. I know there are multiple ways to accomplish this task, but a requirement is that it's done with VB.NET. Any help would be greatly appreciated.
Final code ported from Marco's C# answer
Private Sub CSVmod(ByVal strFileName As String, ByVal newFileName As String)
Dim strLines As String() = File.ReadAllLines(strFileName)
Dim strList As New List(Of String)
Dim strReplace As String = "test"
For Each line In strLines
Dim strValues As String() = line.Split(",")
If (strValues.Length = 14) Then
strValues(3) = strReplace
strList.Add(String.Join(",", strValues))
End If
Next
File.WriteAllLines(newFileName, strList.ToArray())
I'm sorry, but I can write it only in C#.
I think you won't find many problems to convert to VB.NET.
Here is my code:
private void SubstFile(string filename, string newFileName)
{
// Reading all rows of the file
string[] lines = File.ReadAllLines(filename);
List<string> list = new List<string>();
foreach (string line in lines)
{
// For every row I split it with commas
string[] values = line.Split(',');
// Check to have 4 values
if (values.Length == 4)
{
// Substitute fourth value
values[3] = "new value";
// Add modified row to list
list.Add(String.Join(",", values));
}
}
// Save list to new file
File.WriteAllLines(newFileName, list.ToArray());
}
VB.NET version:
Private Sub SubstFile(filename As String, newFileName As String)
' Reading all rows of the file
Dim lines As String() = File.ReadAllLines(filename)
Dim list As List(Of String) = New List(Of String)()
For Each line As String In lines
' For every row I split it with commas
Dim values As String() = line.Split(","c)
' Check to have 4 values
If values.Length = 4 Then
' Substitute fourth value
values(3) = "new value"
' Add modified row to list
list.Add(String.Join(",", values))
End If
Next
' Save list to new file
File.WriteAllLines(newFileName, list.ToArray())
End Sub
Use python....one line of code
df = pandas.read_csv('file.csv)