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

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

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

Reading from text file to ListBox

I am having a bit of trouble reading data from a text file. This almost works, however data in separate lines in the text file is combined to one long line in the ListBox. How else to do it?
Private Sub frmOpretrskAar_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim FILE_NAME As String = "c:\users\claus\onedrive\SLERP\fmr.txt"
Dim objReader As New System.IO.StreamReader(FILE_NAME)
LBmuligeFirmaer.Items.Add(objReader.ReadToEnd)
objReader.Close()
End Sub
Use the ListBox.Items.AddRange method to add an array, in this case it would be an array that represents the lines of the text file. You can get the lines by using IO.File.ReadAllLines method. Here is a quick example:
LBmuligeFirmaer.Items.AddRange(IO.File.ReadAllLines("c:\users\claus\onedrive\SLERP\fmr.txt"))
Its very simple -
List<string> _list = File.ReadAllLines(fileName).ToList();
See the below image -
You can use array.
Try this code:
Dim FILE_NAME As String = "c:\users\claus\onedrive\SLERP\fmr.txt"
Dim AllLines() As String = System.IO.File.ReadAllLines(FILE_NAME)
For i As Integer = 0 To AllLines.Count - 1
LBmuligeFirmaer.Items.Add(AllLines(i))
Next
I can't test this in my IDE currently so tell me if something doesn't work right but I have used something similar:
Imports System.IO
Imports System.Windows.Forms
'assigning a string value to the file's location
Dim FILE_NAME As String = "c:\users\claus\onedrive\SLERP\fmr.txt"
'clearing the listbox
LBmuligeFirmaer.items.clear
'declaring a filereader
Dim fileReader As System.IO.StreamReader
fileReader =
'obtaining file location from string to the stringreader
My.Computer.FileSystem.OpenTextFileReader(FILE_NAME)
Dim stringReader As String
'reading first line
stringReader = fileReader.ReadLine()
'adding line to the listbox
LBmuligeFirmaer.items.add(stringreader)
'reading second line
stringReader = fileReader.ReadLine()
'adding line to listbox
LBmuligeFirmaer.items.add(stringreader)
'and so on...

partial .txt file to datagridview vb.net

i have a user interface form that let's you upload a text file to a datagridview as follows
Sub Datagrid()
Dim sw = System.Diagnostics.Stopwatch.StartNew()
Using stream As System.IO.FileStream = System.IO.File.OpenRead(TextBox1.Text)
Using reader As New System.IO.StreamReader(stream)
Dim line As String = reader.ReadLine()
While (line IsNot Nothing)
Dim columns = line.Split(";")
line = reader.ReadLine()
Dim index = Me.DataGridView1.Rows.Add()
Me.DataGridView1.Rows(index).SetValues(columns)
End While
End Using
End Using
sw.Stop()
End Sub
Well, now my problem is that i don't want to put the full txt file in that datagridview, just from line N.
Is it possible to do that? Like creating a querytabel and selecting a fixed value?
p.e., in line 5 there's always the text "Values:" . Can i select all the lines after that to put in the datagridview? i googled everywhere but found nothing. and there's no "sample" code to give me a start . thank you all !
Dim n As Integer = 5
Dim lines As IEnumerable(Of String) = IO.File.ReadAllLines("textbox1.text").Skip(n)
'Gets every line after a certain line count
'Create a new datatable and add some columns
Dim dt As New DataTable
dt.Columns.AddRange((From columnIndex As Integer In Enumerable.Range(1, lines.First.Split(";"c).Count) Select New DataColumn("Column" & columnIndex.ToString())).ToArray())
'Add each line as a row to the datatable
For Each line As String In lines
dt.Rows.Add(line.Split(";"c))
Next
'Set the datasource of the datagridview
MyDataGridView.DataSource = dt

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.

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