Reading a specified line of an external file on Visual Basic [duplicate] - visual-studio

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.

Related

Center align the data inside a datagrid in visual basic and remove the additional blank row generated at the end of the file

DataGridView1.Rows.Clear()
Try
Dim FileName As String = "C:\Users\xzqt\Desktop\test.csv"
Dim reader As New StreamReader(FileName, Encoding.Default)
Dim Line As String = ""
Dim colexpected As Integer = 3
Dim a As Integer = 0
Do
Line = reader.ReadLine
If Line Is Nothing Then Exit Do
Dim words() As String = Line.Split(",")
DataGridView1.Rows.Add()
For x As Integer = 0 To 2
DataGridView1.Rows(a).Cells(x).Value = words(x)
Next
a = a + 1
Loop
reader.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Output of the data:
Is there a way how I can center align the data from datagrid in visual basic and remove the blank row at the end of it. Attached is the screenshot for further details.Thank you.

How to collect a certain string anywhere in an item in a ListBox?

I have been trying to find out how to collect a string anywhere in a Listbox, I use Visual Basic 2010 and this is more of an request, but there is code I found so you fix the code I found or tell me me an another code to use.
I have tried using ListBoxName.Items.Contains but that did not work, I tried a lot of methods and it would be hard to say all of then at once.
' Split string based on space
Dim textsrtring As String = ListBox.Text
Dim words As String() = textsrtring.Split(New Char() {" "c})
Dim found As Boolean = False
' Use For Each loop over words
Dim word As String
For Each word In words
If ListBox.Items.Contains(word) Then
found = True
Exit For
End If
Next
MessageBox.Show(found)
They were no errors, the message box that appeared kept on telling me false and there is no string when I clearly put it in, no error messages.
You'll need an inner loop to see if each word is contained in your main listbox entry using String.Contains():
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim searchFor As String = TextBox1.Text.Trim
If searchFor.Length > 0 Then
Dim words As String() = searchFor.Split(New Char() {" "c})
Dim found As Boolean = False
Dim foundAt As Integer
' Use For Each loop over words
Dim word As String
For Each word In words
For i As Integer = 0 To ListBox.Items.Count - 1
If ListBox.Items(i).ToString.Contains(word) Then
found = True
foundAt = i
Exit For
End If
Next
If found Then
Exit For
End If
Next
If found Then
ListBox.SelectedIndex = foundAt
Label1.Text = "Search string found."
Else
ListBox.SelectedIndex = -1
Label1.Text = "Search string NOT found."
End If
Else
ListBox.SelectedIndex = -1
Label1.Text = "No search string."
End If
End Sub

Visual Basic split function

Ok so now I'm not getting an error but instead of everything being posted in the listbox it only contains the first line of text from the .txt file. This is the code I changed it too:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim inFile As IO.StreamReader
If IO.File.Exists("StudentList.txt") = True Then
inFile = IO.File.OpenText("StudentList.txt")
For index As Integer = 0 To inFile.Peek = -1
Dim splits = inFile.ReadLine.Split(","c)
Member(index).ID = splits(0)
Member(index).lastName = splits(1)
Member(index).firstName = splits(2)
Member(index).middleName = splits(3)
Member(index).grade = splits(4)
Member(index).period = splits(5)
ListBox1.Items.Add(Member(index).ID.PadLeft(10) & " " & Member(index).lastName & " " & Member(index).firstName)
Next
inFile.Close()
Else
MessageBox.Show("error", "error", MessageBoxButtons.OK)
End If
End Sub
The problem is that you're trying to assign a string array to a Member. That is, you have:
Member(index) = infile.ReadLine.Split(",", c);
You need to assign each field:
Dim splits = infile.ReadLine.Split(",", c);
Member(index).ID = splits(0);
Member(index).lastName = splits(1);
... etc.
Update after OP edit
I suspect the problem now is that your For loop is executing only once, or index isn't being incremented. I don't know where you came up with that wonky infile.Peek = -1 thing, but I suspect it doesn't work the way you think it does. Use something more conventional, like this.
Dim index As Integer = 0
For Each line As String In File.ReadLines("StudentList.txt")
Dim splits = line.Split(",", c)
Member(index).ID = splits(0)
' etc.
ListBox1.Add(...)
Index = Index + 1
Next

How to write data to a file in Visual Studios?

I'm writing a program that reads an input file that contains a line:
Scott Atchison,200,74
The file contains around 30 different lines of data. I know how to read in the file. After the file is read in it is split and then a calculation needs to be done (I know how to do that).
However, the problem that I have is the output file, I can get only the last line of the input file to the output file. This is what I have right now:
Public Class BMI
Dim data As String
Dim strName As String
Dim intWeight As Integer
Dim intHeight As Integer
Dim decBMI As Decimal
Private Sub btnInputFile_Click(sender As System.Object, e As System.EventArgs) Handles btnOpenFile.Click
'User chooses a file
OpenFile.ShowDialog()
'Choose a file name into a label
lblFileInput.Text = OpenFile.FileName
Dim inputFile As New IO.StreamReader(lblFileInput.Text)
Do While (inputFile.Peek() > -1)
data = inputFile.ReadLine
Dim fields() As String = data.Split(",")
strName = fields(0)
intWeight = fields(1)
intHeight = fields(2)
txtData.Text = txtData.Text & data & vbNewLine
Loop
FileClose()
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles btnSaveFile.Click
SaveFile.ShowDialog()
lblFileOutput.Text = SaveFile.FileName
Dim output As IO.StreamWriter
output = New IO.StreamWriter(lblFileOutput.Text)
output.WriteLine(data)
End Sub
Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs) Handles Button1.Click
decBMI = (intWeight * 703 / (intHeight ^ 2))
data = strName & ", " & decBMI
End Sub
End Class
Wouldn't it write a line until all 30 lines are read, or Am I missing something, like a while loop? Any help would be appreciated.
It would be nice if you gave us a nice, executable, snippet of code, including declarations of all your variables. For instance, where is "data" defined. What is the relationship between both chunks of code? Are they in the same procedure?
The first thing I notice is that you are splitting each line, "data", into fields, saving them into variables, which you just ignore. You then append "data" to a text box.
Assuming that "data" is shared between the two chunks of code, then reason for your problem is that the value being written to the streamwriter is the last value of "data", which happens to be the last line that was read into it.

Visual Basic Deleting Unmodified Files

The following code will extract files from one Folder and Place them another as you can see. But I am trying to delete the files that have not been modified in the past 3 months, and it does not delete any files at all.
Code:
Imports System.IO
Public Class frmExtractionator
Dim txtFiles1 As Control
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim sourceDirectory As String = "E:\CopierFolderforTestDriveCapstone"
Dim archiveDirectory As String = "E:\FilesExtracted"
Try
Dim txtFiles = Directory.EnumerateFiles(sourceDirectory)
If (Not System.IO.Directory.Exists(archiveDirectory)) Then
System.IO.Directory.CreateDirectory(archiveDirectory)
End If
For Each currentFileLoc As String In txtFiles
Dim fileName = currentFileLoc.Substring(sourceDirectory.Length + 1)
File.Move(currentFileLoc, Path.Combine(archiveDirectory, fileName))
Try
Dim di As DirectoryInfo = New DirectoryInfo(sourceDirectory)
Dim fi As FileInfo() = di.GetFiles()
For Each currentFile As FileInfo In fi
File.Move(currentFile.FullName, Path.Combine(archiveDirectory, currentFile.Name))
Dim dt As DateTime = currentFile.LastWriteTime
' Add 3 months to the last write and check if it is less than today '
If dt.AddMonths(3) < DateTime.Today Then
File.Delete(currentFile.FullName)
End If
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
End Sub
End Class

Resources