Read text file with delimiter - vb.net

i want to read text file and from the fifth line take only the first column before (;) this my code to browse and read text :
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim OpenFile As New OpenFileDialog
OpenFile.FileName = ""
OpenFile.Filter = "Fichier Texte (*.pnp)|*.pnp"
OpenFile.ShowDialog()
Try
Dim lire As New System.IO.StreamReader(OpenFile.FileName)
RichTextBox1.Text = lire.ReadToEnd
lire.Close()
Catch ex As Exception
End Try
End Sub
End Class
help me please

You could try something like this:
Dim lineYouWantToRead As Int32 = 5
Dim fieldYouWantToRead As Int32 = 1
Dim capturedValue As String = ""
Using fileReader As New FileIO.TextFieldParser(OpenFile.FileName)
fileReader.TextFieldType = FileIO.FieldType.Delimited
fileReader.SetDelimiters(";")
While fileReader.LineNumber <= lineYouWantToRead - 1
Dim currentLine As String() = fileReader.ReadFields()
capturedValue = currentLine(fieldYouWantToRead - 1)
End While
End Using
RichTextBox1.Text = capturedValue
Let us know if that is any help.

Related

Remove duplicate characters from strings and find the shortest

I can not figure out how to select from the result or the shortest line itself or its number
(Yes, the solution is needed in such ancient operators)
Imports System.IO
Public Class Form1
Sub readputh(ByRef s As String)
s = ""
OpenFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
OpenFileDialog1.ShowDialog()
Do While s = ""
s = OpenFileDialog1.FileName
Loop
End Sub
Sub writeputh(ByRef s As String)
s = ""
SaveFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
SaveFileDialog1.ShowDialog()
Do While s = ""
s = SaveFileDialog1.FileName
Loop
End Sub
Sub ch(ByVal Str As String, ByRef Res As String)
Dim a As Char
Res = Mid(Str, 1, 1)
For i = 2 To Len(Str)
a = CChar(Mid(Str, i, 1))
If InStr(Res, a) = 0 Then
Res = Res + a
End If
Next
End Sub
Sub resh(ByVal filename1 As String, ByVal filename2 As String, ByRef lb1 As ListBox, ByRef lb2 As ListBox)
Dim rf As StreamReader
Dim wf As StreamWriter
Dim s1, s2, s3 As String
s2 = ""
s3 = ""
Try
rf = New StreamReader(filename1)
wf = New StreamWriter(filename2, True)
Do While Not rf.EndOfStream()
s1 = rf.ReadLine()
lb1.Items.Add(s1)
ch(s1, s2)
wf.WriteLine(s2)
lb2.Items.Add(s2)
Loop
wf.Close()
rf.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim filename1, filename2 As String
readputh(filename1)
writeputh(filename2)
resh(filename1, filename2, ListBox1, ListBox2)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
End
End Sub
End Class
Input file:
youtubeyoutubeyotube
dogdogdogdog
geeksforgeeks
Output file:
youtbe
dog
geksfor
But I expect Output file of only "dog"
I just couldn't handle the old code. One based functions? No! You can translate it back it you want but output is now dog.
Private Function GetOpenPath() As String
OpenFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Return OpenFileDialog1.FileName
Else
Return Nothing
End If
End Function
Private Function GetSavePath() As String
SaveFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Return SaveFileDialog1.FileName
Else
Return Nothing
End If
End Function
Private Function ch(ByVal Str As String) As String
Dim a As Char
Dim Res = Str.Substring(0, 1)
For i = 1 To Str.Length - 1
a = CChar(Str.Substring(i, 1))
If Res.IndexOf(a) = -1 Then
Res &= a
End If
Next
Return Res
End Function
Sub resh(ByVal filename1 As String, ByVal filename2 As String)
Dim lines = File.ReadAllLines(filename1)
Dim NewLines As New List(Of String)
For Each line In lines
Try
ListBox1.Items.Add(line)
Dim s2 = ch(line)
NewLines.Add(s2)
ListBox2.Items.Add(s2)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
Dim Shortest = NewLines.OrderByDescending(Function(s) s.Length).Last()
File.WriteAllText(filename2, Shortest)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OpenPath = GetOpenPath()
Dim SavePath = GetSavePath()
If String.IsNullOrEmpty(OpenPath) OrElse String.IsNullOrEmpty(SavePath) Then
MessageBox.Show("You must provide a file. Try again.")
Return
End If
resh(OpenPath, SavePath)
End Sub

Download a file from google drive

First of all, sorry for my english. Second, I want to make an app that, at every launch download a .txt file from google drive, the file is defined (I mean, it's in drive). It's just a single file, but, when I launch the app, the file is downloaded, but dosen't contain anything..
Here is my code:
Private Function ReadLine(ByVal Line As Integer, ByVal lista As List(Of String)) As String
Return lista(Line - 1)
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If My.Computer.Network.IsAvailable() = True Then
Try
My.Computer.FileSystem.DeleteFile("C:\WINDOWS\" & fisier)
Catch ex As Exception
End Try
My.Computer.Network.DownloadFile("https://doc-14-7c-docs.googleusercontent.com/docs/securesc/17t22h2a63tpkhdgv047v6i0s5a9o8bm/qgqjocmi87jt0up72gfpg9dseeo3pt84/1458396000000/07699472972018131827/07699472972018131827/0B8iVIf__yN1FUDV1STNWODJUYms?e=download&nonce=5jnki0mtgo520&user=07699472972018131827&hash=0gi5r6k7rm2uob14062tlbsk0nhpkoo1", _
"C:\WINDOWS\" & fisier)
Dim reader As New IO.StreamReader("C:\WINDOWS\" & fisier)
Dim lista As New List(Of String)
While Not reader.EndOfStream
lista.Add(reader.ReadLine)
End While
reader.Close()
If My.Computer.FileSystem.FileExists(fisier2) = False Then
lblWould.Text = ReadLine(1, lista)
Else
Dim nr As Integer
nr = Val(My.Computer.FileSystem.ReadAllText(fisier2))
nrx = nr
End If
Dim contain As String = My.Computer.FileSystem.ReadAllText("C:\WINDOWS\" & fisier)
contain = contain.Replace(lblWould.Text, "SEEN!")
My.Computer.FileSystem.WriteAllText("C:\WINDOWS\" & fisier, contain, False)
Else
MsgBox("Trebuie sa fi connectat la internet!")
Me.Close()
End If
End Sub
Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnYes.Click, btnNo.Click
Dim reader As New IO.StreamReader("C:\WINDOWS\" & fisier)
Dim lista As New List(Of String)
Dim a As String
While Not reader.EndOfStream
a = reader.ReadLine()
If Not a = "SEEN!" Then
lista.Add(reader.ReadLine)
End If
End While
lblWould.Text = lista(nrx + 1)
nrx += 1
Dim contain As String = My.Computer.FileSystem.ReadAllText("C:\WINDOWS\" & fisier)
contain = contain.Replace(lblWould.Text, "SEEN!")
My.Computer.FileSystem.WriteAllText("C:\WINDOWS\" & fisier, contain, False)
End Sub`
Thanks!

How to read a specific line from a text file in VB

I am creating a program that is supposed to write text into a text file, and should be able to read specific lines from a text file in VB (so if i needed to read a specific name I could select line 5 and it would display in the textbox). I am able to read the text from the text file but I do not know how to control a specific line.
Here is my code:
Public Class Form1
Private Sub btnSubmit_Click(sender As System.Object, e As System.EventArgs) Handles btnSubmit.Click
Dim writer As New System.IO.StreamWriter("/text.txt", True)
writer.WriteLine(txtFirstName.Text)
writer.WriteLine(txtLastName.Text)
writer.WriteLine("-------------------------------------")
writer.Close()
End Sub
Private Sub btnRead_Click(sender As System.Object, e As System.EventArgs) Handles btnRead.Click
Dim reader As New System.IO.StreamReader("/text.txt")
Dim FirstName, LastName As String
FirstName = reader.ReadLine()
LastName = reader.ReadLine()
reader.Close()
txtFirstName.Text = FirstName
txtLastName.Text = LastName
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtFirstName.Clear()
txtLastName.Clear()
End Sub
End Class
Any help would be appreciated. Thanks!
You will have to read all lines up to the one you're interested in. For example:
Function ReadLineWithNumberFrom(filePath As String, ByVal lineNumber As Integer) As String
Using file As New StreamReader(filePath)
' Skip all preceding lines: '
For i As Integer = 1 To lineNumber - 1
If file.ReadLine() Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
Next
' Attempt to read the line you're interested in: '
Dim line As String = file.ReadLine()
If line Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
' Succeded!
Return line
End Using
End Function
This is because lines of text are variable-length records, and there is no way to guess the exact file offset where a specific line begins — not without an index.
If you frequently need to load a specific line, you have some more options:
Load the complete text file into memory, e.g. by using File.ReadAllLines("Foobar.txt"). This returns a String() array which you can access by line number directly.
Create a line number index manually. That is, process a text file line by line, and fill a Dictionary(Of Integer, Integer) as you go. The keys are line numbers, and the values are file offsets. This allows you to .Seek right to the beginning of a specific line without having to keep the whole file in memory.
Try this:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim reader As New System.IO.StreamReader("C:\text.txt")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
txtFirstName.Text = ReadLine(5, allLines)
txtLastName.Text = ReadLine(6, allLines)
End Sub
Public Function ReadLine(lineNumber As Integer, lines As List(Of String)) As String
Return lines(lineNumber - 1)
End Function
If you had a file with this:
Line 1
Line 2
Line 3
Line 4
My Name
My LastName
your name textbox will have 'My Name' and your LastName textbox will have 'My LastName'.
This is very simple, try this:
Dim strLineText As String
Dim intLineNumber As Integer
LineNumber=3
myLine = File.ReadAllLines("D:\text.txt").ElementAt(LineNumber).ToString
Yet another option
Private Function readNthLine(fileAndPath As String, lineNumber As Integer) As String
Dim nthLine As String = Nothing
Dim n As Integer
Try
Using sr As StreamReader = New StreamReader(fileAndPath)
n = 0
Do While (sr.Peek() >= 0) And (n < lineNumber)
sr.ReadLine()
n += 1
Loop
If sr.Peek() >= 0 Then
nthLine = sr.ReadLine()
End If
End Using
Catch ex As Exception
Throw
End Try
Return nthLine
End Function
i tried this and it works fine. using VB Express
content inside test.txt:
line1
line2
1
John
then in the form i add
textbox1
textbox2
label1
label2
and a button.
code inside the button:
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim myLine As String
Dim lineNumber0 As Integer
lineNumber0 = 0
Dim lineNumber1 As Integer
lineNumber1 = 1
Dim lineNumber2 As Integer
lineNumber2 = 2
Dim lineNumber3 As Integer
lineNumber3 = 3
TextBox1.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber0).ToString
TextBox2.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber1).ToString
Label1.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber2).ToString
Label2.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber3).ToString
End Sub
Here's a simple but effective solution:
Dim Reader As String = System.IO.File.ReadAllLines("C:\File.txt")(1)
MsgBox("Line 1: " + Reader)
The MsgBox should show the first line of C:\File.txt.

Listview items and saving them as .csv

I'm doing this project where I need to save the names of the items from a listview to a .csv
Imports System.IO
Public Class cv7import
Private Sub cv7import_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim caminho As String
caminho = "C:\Documents and Settings\Software\Ambiente de trabalho\cv7import"
Dim returnValue As String()
returnValue = Environment.GetCommandLineArgs()
If returnValue.Length > 1 Then
MessageBox.Show(returnValue(1).ToString())
Else
MessageBox.Show("Nothing")
End If
' Set ListView Properties
lstvicon.View = View.Details
lstvicon.GridLines = False
lstvicon.FullRowSelect = True
lstvicon.HideSelection = False
lstvicon.MultiSelect = True
' Create Columns Headers
lstvicon.Columns.Add("Nome")
lstvicon.Columns.Add("Extensão")
lstvicon.Columns.Add("Tamanho")
lstvicon.Columns.Add("Data Modificação")
Dim DI As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(caminho)
Dim files() As System.IO.FileInfo = DI.GetFiles
Dim file As System.IO.FileInfo
Dim li As ListViewItem
For Each file In files
li = lstvicon.Items.Add(file.Name)
li.SubItems.Add(file.Extension)
li.SubItems.Add(file.Length)
li.SubItems.Add(file.LastWriteTimeUtc)
'li.SubItems.Add(FileDialog)
Next
End Sub
Private Sub btnimp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnimp.Click
' Creates a csv File
Dim csv As New System.IO.StreamWriter("C:\Documents and Settings\Software\Ambiente de trabalho\cv7import\teste.csv", True)
lstvicon.SelectedItems.CopyTo(csv)
csv.Close()
End Sub
End Class
That's what I got but I can't seem to get it to write on the .txt.
I have no idea where to go from here and i've been going around this for hours, so any help would be apreciated.
I think that you want something like this:
' Creates a csv File
Using csv As New System.IO.StreamWriter("C:\Documents and Settings\Software\Ambiente de trabalho\cv7import\teste.csv", True)
For Each oItem As ListViewItem In ListView1.Items
csv.WriteLine(String.Format("""{0}"",""{1}"",{2},{3}", oItem.Text, oItem.SubItems(0).Text, oItem.SubItems(1).Text, oItem.SubItems(2).Text )
Next
End Using
You will probably need to clean up the csv formatting, but this should give you an idea.

Read Text File and Output Multiple Lines to a Textbox

I'm trying to read a text file with multiple lines and then display it in a textbox. The problem is that my program only reads one line. Can someone point out the mistake to me?
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private BagelStreamReader As StreamReader
Private PhoneStreamWriter As StreamWriter
Dim ResponseDialogResult As DialogResult
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
'Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
'Is file already open
If PhoneStreamWriter IsNot Nothing Then
PhoneStreamWriter.Close()
End If
With OpenFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
'If ResponseDialogResult <> DialogResult.Cancel Then
' PhoneStreamWriter = New StreamWriter(OpenFileDialog1.FileName)
'End If
Try
BagelStreamReader = New StreamReader(OpenFileDialog1.FileName)
DisplayRecord()
Catch ex As Exception
MessageBox.Show("File not found or is invalid.", "Data Error")
End Try
End Sub
Private Sub DisplayRecord()
Do Until BagelStreamReader.Peek = -1
TextBox1.Text = BagelStreamReader.ReadLine()
Loop
'MessageBox.Show("No more records to display.", "End of File")
'End If
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
With SaveFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
PhoneStreamWriter.WriteLine(TextBox1.Text)
With TextBox1
.Clear()
.Focus()
End With
TextBox1.Clear()
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
PhoneStreamWriter.Close()
Me.Close()
End Sub
End Class
Here is a sample textfile:
Banana nut
Blueberry
Cinnamon
Egg
Plain
Poppy Seed
Pumpkin
Rye
Salt
Sesame seed
You're probably only getting the last line in the file, right? Your code sets TextBox1.Text equal to BagelSteramReader.ReadLine() every time, overwriting the previous value of TextBox1.Text. Try TextBox1.Text += BagelStreamReader.ReadLine() + '\n'
Edit: Though I must steal agree with Hans Passant's commented idea on this; If you want an more efficient algorithm, File.ReadAllLines() even saves you time and money...though I didn't know of it myself. Darn .NET, having so many features...
I wrote a program to both write to and read from a text file. To write the lines of a list box to a text file I used the following code:
Private Sub txtWriteToTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtWriteToTextfile.Click
Dim FileWriter As StreamWriter
FileWriter = New StreamWriter(FileName, False)
' 3. Write some sample data to the file.
For i = 1 To lstNamesList.Items.Count
FileWriter.Write(lstNamesList.Items(i - 1).ToString)
FileWriter.Write(Chr(32))
Next i
FileWriter.Close()
End Sub
And to read and write the contents of the text file and write to a multi-line text box (you just need to set the multiple lines property of a text box to true) I used the following code. I also had to do some extra coding to break the individual words from the long string I received from the text file.
Private Sub cmdReadFromTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReadFromTextfile.Click
Dim sStringFromFile As String = ""
Dim sTextString As String = ""
Dim iWordStartingPossition As Integer = 0
Dim iWordEndingPossition As Integer = 0
Dim iClearedTestLength As Integer = 0
Dim FileReader As StreamReader
FileReader = New StreamReader(FileName)
sStringFromFile = FileReader.ReadToEnd()
sTextString = sStringFromFile
txtTextFromFile.Text = ""
Do Until iClearedTestLength = Len(sTextString)
iWordEndingPossition = CInt(InStr((Microsoft.VisualBasic.Right(sTextString, Len(sTextString) - iWordStartingPossition)), " "))
txtTextFromFile.Text = txtTextFromFile.Text & (Microsoft.VisualBasic.Mid(sTextString, iWordStartingPossition + 1, iWordEndingPossition)) & vbCrLf
iWordStartingPossition = iWordStartingPossition + iWordEndingPossition
iClearedTestLength = iClearedTestLength + iWordEndingPossition
Loop
FileReader.Close()
End Sub