Remove a line from text file vb.net - 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.

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

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()

How to remove a line of text from a txt file

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)

Splitting a CSV Visual basic

I have a string like
Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132, 460
Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455
in a file
in two separate lines. I am reading it from the textbox. I have to output ab563372363_C/R and ab563372356_C/R in a text box. I am trying to use the split function for that but its not working..
Dim splitString as Array
results = "test.txt"
Dim FileText As String = IO.File.ReadAllText(results) 'reads the above contents from file
splitString = Split(FileText, ",", 14)
TextBox2.text = splitString(1) & splitString(13)
for the above code, it just prints the whole thing.. What's wrong?
Try this
Private Function GetRequiredText() As List(Of String)
Dim requiredStringList As New List(Of String)
Dim file = "test.txt"
If FileIO.FileSystem.FileExists(file) Then
Dim reader As System.IO.StreamReader = System.IO.File.OpenText(file)
Dim line As String = reader.ReadLine()
While line IsNot Nothing
requiredStringList.Add(line.Split(",")(1))
line = reader.ReadLine()
End While
reader.Close()
reader.Dispose()
End If
Return requiredStringList
End Function
This will read the file line by line and add the item you require to a list of strings which will be returned by the function.
Returning a List(Of String) may be overkill, but it's quite simple to illustrate and to work with.
You can then iterate through the list and do what you need with the contents of the list.
Comments welcome!!
Also this might work...
Dim query = From lines In System.IO.File.ReadAllLines(file) _
Select lines.Split(",")(1)
this will return an IEnumerable(Of String)
Enjoy
First
Since you are reading the whole text, your FileText would be ending like this:
Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132,460
\r\n
Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455
So when you are referencing to your splitStringwith those indexes (1, 13) your result might probably be wrong.
Second
Try to specify what kind of type your array is, Dim splitString as Array should be Dim splitString As String()
Third
Make your code more readable/maintainable and easy to edit (not only for you, but others)
The Code
Private const FirstIndex = 1
Private const SecondIndex = 12
Sub Main
Dim myDelimiter As Char
Dim myString As String
Dim mySplit As String()
Dim myResult1 As String
Dim myResult2 As String
myDelimiter = ","
myString += "Query_1,ab563372363_C/R,100.00,249,0,0,1,249,1,249,1e-132, 460"
myString += "Query_1,ab563372356_C/R,99.60,249,1,0,1,249,1,249,5e-131, 455"
mySplit = myString.Split(myDelimiter)
myResult1 = mySplit(FirstIndex)
myResult2 = mySplit(SecondIndex)
Console.WriteLine(myResult1)
Console.WriteLine(myResult2)
End Sub

Read text file with tab and carraige return format to store them in array

I have to text file in the following format :
Word[tab][tab]Word[Carriage Return]
Word[tab][tab]Word[Carriage Return]
Word[tab][tab]Word[Carriage Return]
I want to get all the words before the tab into one array or to create a new text file and the all the words after the tab into another array or create a new text file too.
Here my function to get the words before tab into an array :
Protected Sub MakeWordListBeforeTab()
Dim filename As String = "D:\lao\00001.txt"
'read from file'
Dim MyStream As New StreamReader(filename)
'words before tab
Dim WordBeforeTabArr() As String = MyStream.ReadToEnd.Split(CChar("\t"))
MyStream.Close()
'test to see the word in array
For d As Integer = 0 To WordBeforeTabArr.Length - 1
MsgBox(WordBeforeTabArr(d))
Next
End Sub
I wrote the above function to get all words before tab but I got all the words into array. I've been trying to use the Split method above. What is another method to split those words ? Can anyone show me some code to get this done right ?
I know this can be done with regular expression but I don't know regex yet. If you can show me how to get this done with regex it'll be awesome. Thanks.
You could try the split function on String. It could be used like this:
Dim lines() As String = IO.File.ReadAllLines(filename)
For Each line As String In lines
Dim words() As String = _
line.Split(New Char() {vbTab}, StringSplitOptions.RemoveEmptyEntries)
Next
The words array for each line would the two words. One word at each position. You could fill your two arrays or write the values out to a text file or file as you split the lines of the input file in the loop.
First of all above code is not compiling: See proper code as follows:
Dim lines() As String = IO.File.ReadAllLines(test_Filename)
For Each line As String In lines
Dim words() As String = _
line.Split("\t".ToCharArray()(0), StringSplitOptions.RemoveEmptyEntries)
Next