vb.net appendline substring error - vb.net

I have this code in vb:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles browsebtn.Click
OpenFileDialog1.Filter = "Text Files|*.txt"
OpenFileDialog1.Title = "Select Log File"
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim filename As String = OpenFileDialog1.FileName
Using streamreader As New StreamReader(filename)
While streamreader.Read
Dim line As String = streamreader.ReadLine()
Dim date1 As String = line.Substring(6, 6)
Dim writer = New StreamWriter("c:\" + date1 + ".txt")
writer = File.AppendText(line)
writer.Close()
End While
End Using
End If
End Sub
End Class
When I run it, it gives me an error:
"startIndex cannot be larger than length of string."
What am I doing wrong?

Several comments make no sense like the error happening at the end of the loop or how checking a string length can result in a File Access error. Try something this:
Dim Line as String
Dim Date1 As String
While streamreader.Read
Line = streamreader.ReadLine()
If Line.Length > 12 Then
date1 = line.Substring(6, 6)
Using sw As New StreamWriter("c:\" + date1 + ".txt")
sw.Write(line)
End Using
End If
End While

Related

Reading .txt files using StreamReader

I am having an issue, I have a program I'm working on and I have to be able to read multiple .txt files one after the other to update a string array called words(). The main problem is the first file I upload goes into the files()string array, when I run my drag and drop event the array is full and won't let me upload second. how do I reset the files()array after it has been uploaded successfully.
sample code:
Dim words(7) As String
Dim i As Integer = 0
Public Sub frmMain_DragDrop(sender As Object, e As DragEventArgs) Handles MyBase.DragDrop
Dim word As String = ""
Try
Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
For Each path In files
MsgBox(path)
Dim sr As New StreamReader(path)
Do Until sr.Peek = -1
word = sr.ReadLine()
words(i) = word
frmDefaultkWh.lbDefaultkWh.Items.Add(cbAppliances.Items(i) + " = " + words(i))
i = i + 1
Loop
Next
GetPower()
Catch ex As Exception
'MessageBox.Show(ex.ToString())
End Try
End Sub
Private Sub frmMain_DragEnter(sender As Object, e As DragEventArgs) Handles MyBase.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
I believe this is because you are not resetting i, which means that eventually i increments out of the range of your words() array which is only size 7, which by the way will also throw an error if one of those files has more than 7 lines.
For Each path In files
i = 0 'reset counter
MsgBox(path)
Dim sr As New StreamReader(path)
Do Until sr.Peek = -1
word = sr.ReadLine()
words(i) = word
frmDefaultkWh.lbDefaultkWh.Items.Add(cbAppliances.Items(i) + " = " + words(i))
i = i + 1
Loop
Next

How to change filepath when check a radiobutton? Visual basic

My problem here is that i have 3 radiobuttons for 3 different categories:
Huse Folii and Altele.
The idea is when i select a radiobutton,the filepath will change to Huse,Folii or Altele.
For example i tried to make _path :
Dim _path As String = IO.Path.Combine("C:\Descriere\Huse\")
then use the _path here:
Dim ioFile As New System.IO.StreamReader(_path + "a.txt")
but it didn't worked,for sure i do something wrong,but i can't find how or where to use that _path...
Here is the code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
On Error Resume Next
TextBox1.Clear()
If RadioButton1.Checked = True Then
Dim _path As String = IO.Path.Combine("C:\Descriere\Huse\")
End If
If RadioButton2.Checked = True Then
Dim _path As String = IO.Path.Combine("C:\Descriere\Folii\")
End If
If RadioButton3.Checked = True Then
IO.Path.
Dim _path As String = IO.Path.Combine("C:\Descriere\Altele\")
End If
Dim ioFile As New System.IO.StreamReader(_path + "a.txt")
Dim lines As New List(Of String)
Dim rnd As New Random()
Dim line As Integer
While ioFile.Peek <> -1
lines.Add(ioFile.ReadLine())
End While
line = rnd.Next(lines.Count + 1)
TextBox1.AppendText(lines(line).Trim())
ioFile.Close()
ioFile.Dispose()
Dim ioFile2 As New System.IO.StreamReader(path:=+"core.txt")
Dim lines2 As New List(Of String)
Dim rnd2 As New Random()
Dim line2 As Integer
While ioFile2.Peek <> -1
lines2.Add(ioFile2.ReadLine())
End While
line2 = rnd2.Next(lines2.Count + 1)
TextBox1.AppendText(lines2(line2).Trim())
ioFile2.Close()
ioFile2.Dispose()
Dim ioFile3 As New System.IO.StreamReader(path:=+"x.txt")
Dim lines3 As New List(Of String)
Dim rnd3 As New Random()
Dim line3 As Integer
While ioFile3.Peek <> -1
lines3.Add(ioFile3.ReadLine())
End While
line3 = rnd3.Next(lines3.Count + 1)
TextBox1.AppendText(lines3(line3).Trim())
ioFile3.Close()
ioFile3.Dispose()
TextBox1.Text = Replace(TextBox1.Text, "BRAND", TextBox2.Text)
TextBox1.Text = Replace(TextBox1.Text, "MODEL", TextBox3.Text)
Dim count As Integer = 0
count = TextBox1.Text.Split(" ").Length - 1
Label5.Text = "Caractere:" & Len(TextBox1.Text)
End Sub
You are using IO.Path.Combine but you have nothing to Combine at the place of use in your code. You have to use IO.Path.Combine later in your code because this is a method to Combine part of a path and a filename e.g. set your _path first and combine in a second step. Please note this code is not tested for your needs, because your coding is not clear to me.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim directoryName As String = "D:\"
On Error Resume Next
TextBox1.Clear()
If RadioButton1.Checked = True Then
directoryName = "D:\Descriere\Huse"
End If
If RadioButton2.Checked = True Then
directoryName = "D:\Descriere\Folii"
End If
If RadioButton3.Checked = True Then
'//--- IO.Path.
directoryName = "D:\Descriere\Altele"
End If
Dim ioFile As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "a.txt"))
...
Dim ioFile2 As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "core.txt"))
...
Dim ioFile3 As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "x.txt"))
...
End Sub
Please use the debugger of your IDE because your code isn't clean e.g. a hanging aroung IO.Path.

Read text file with delimiter

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.

Print Preview not displaying file

I am working on a menu strip Print Preview event. i worked out the following procedure to view a pdf file located in the same path as my workbook.
Private WithEvents docPrint As New PrintDocument()
' Declare a string to hold the entire document contents.
Private documentContents As String
' Declare a variable to hold the portion of the document that
' is not printed.
Private stringToPrint As String
Private Sub ReadDocument()
Dim xlWBPath As String = Globals.ThisWorkbook.Application.ActiveWorkbook.Path
Dim docName As String = xlWBPath & "\" & "CustomRanges.pdf"
docPrint.DocumentName = docName
Dim stream As New FileStream(docName, FileMode.Open)
Try
Dim reader As New StreamReader(stream)
Try
documentContents = reader.ReadToEnd()
Finally
reader.Dispose()
End Try
Finally
stream.Dispose()
End Try
stringToPrint = documentContents
End Sub
Private Sub prnPrvStripCustomRange_Click(sender As Object, e As EventArgs) Handles prnPrvStripCustomRanges.Click
ReadDocument()
prnPrvCustomRanges.Document = docPrint
prnPrvCustomRanges.ShowDialog()
End Sub
The dialog pops up on click, but my document page is blank. I have another event for printing and that one prints the same document. So I don't understand what I am doing wrong on my preview.
Here is my print procedure:
Private Sub prnCustonPages_Click(sender As Object, e As EventArgs) Handles prnCustonPages.Click
Dim xlWBPath As String = Globals.ThisWorkbook.Application.ActiveWorkbook.Path
Dim docName As String = xlWBPath & "\" & "CustomRanges.pdf"
docPrint.DocumentName = docName
prnPrtCustomRanges.Document = docPrint
prnPrtCustomRanges.PrinterSettings = docPrint.PrinterSettings
prnPrtCustomRanges.AllowSomePages = True
If prnPrtCustomRanges.ShowDialog = DialogResult.OK Then
docPrint.PrinterSettings = prnPrtCustomRanges.PrinterSettings
docPrint.Print()
End If
End Sub

Importing last line of a .csv file

I have a csv file and I need to get the last line only into seperate textboxes.
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub btnConditions_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConditions.Click
Using reader As New StreamReader("C:\temp\Apr12log.txt")
Dim line As String = reader.ReadLine()
Dim fields() As String = line.Split(",".ToCharArray())
Dim fileDate = CDate(fields(0))
Dim fileTime = fields(1)
Dim fileTemp = fields(2)
Dim fileHum = fields(3)
Dim fileWindSpeed = fields(4)
Dim fileWindGust = fields(5)
Dim fileWindBearing = fields(6)
While line IsNot Nothing
line = reader.ReadLine()
End While
txtDate.Text = CStr(fileDate)
End Using
End Sub
End Class
It only inputs the first line I am not sure how to get the last line only.
example of txtfile
01/04/12,00:00,5.4,80,3.0,4.5,9.6,261,0.0,0.0,1025.0,1.0,16.8,43,4.0,3.8,5.4,0.0,0,0.0
Alternatively, you could use the System.IO.File ReadLines() function, which gives you an enumerable that you can call Last() on.
Private Sub btnConditions_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConditions.Click
Dim line As String = System.IO.File.ReadLines("C:\temp\Apr12log.txt").Last()
Dim fields() As String = line.Split(",".ToCharArray())
Dim fileDate = CDate(fields(0))
Dim fileTime = fields(1)
Dim fileTemp = fields(2)
Dim fileHum = fields(3)
Dim fileWindSpeed = fields(4)
Dim fileWindGust = fields(5)
Dim fileWindBearing = fields(6)
txtDate.Text = CStr(fileDate)
End Sub
You're only reading in one line. Instead use ReadToEnd() and then split by a new line, like so:
Dim lines() As String = reader.ReadToEnd().Split(Environment.NewLine)
Then you can move to the last line:
Dim line As String = lines(lines.Length - 1)
You can get what you want with a couple of edits to your existing code:
Shift
While line IsNot Nothing
line = reader.ReadLine()
End While
To just after
Dim line As String = reader.ReadLine()
Add another
Dim line2 As String = Nothing
And insert
line2 = line
Into the While loop, i.e.
While line IsNot Nothing
line2 = line
line = reader.ReadLine()
End While
Now line2 is the last line in the file.
Try this:
Dim lines() As String = File.ReadAllLines("C:\temp\Apr12log.txt")
lastLine = lines(lines.Length - 1)