Reading .txt files using StreamReader - vb.net

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

Related

Get percentage of files copied from a list

I have an app that copies files in a list to a new directory. I'm trying to get the progress bar to work but my formula results with a System.OverflowException: Arithmetic operation resulted in an over flow. I've looked at other examples using file copying but they are centered on using the source folder divided by destination folder. Mines a little bit different because I'm using files in a list.
Thank you for the help.
Code
Dim progress = fileCount * 100 / fileList.Count()
BackgroundWorker1.ReportProgress(progress)
Code for getting file Count
Dim FILE_NAME As String
FILE_NAME = txtFileName.Text
Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
fCount = 0
For i = 0 To fileNames.Count() - 1
Dim fileName = fileNames(i)
sFileToFind = location & "\" & fileName & "*.*"
Dim paths = IO.Directory.GetFiles(location, fileName, IO.SearchOption.AllDirectories)
If Not paths.Any() Then
System.IO.File.AppendAllText(orphanedFiles, fileName & vbNewLine)
Else
For Each pathAndFileName As String In paths
If System.IO.File.Exists(pathAndFileName) = True Then
sRegLast = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
Dim toFileLoc = System.IO.Path.Combine(createXMLFldr, sRegLast)
Dim moveToFolder = System.IO.Path.Combine(MoveLocation, "XML files", sRegLast)
'if toFileLoc = XML file exists move it into the XML files folder
If System.IO.File.Exists(toFileLoc) = False Then
System.IO.File.Copy(pathAndFileName, moveToFolder)
System.IO.File.AppendAllText(ListofFiles, sRegLast & vbNewLine)
fCount = fCount + 1
XMLFilename = (sRegLast) + vbCrLf
End If
End If
Next
End If
Dim srcCount = paths.Count()
If (paths.Count() = 0) Then
srcCount = 1
End If
Dim progress = CType(fCount * 100 / srcCount, Integer)
BackgroundWorker1.ReportProgress(progress)
Next
This for BackGroundWorker, I hope will this can resolve the trouble of the next call to update progress bar:
'This button1_click event to begin or stop async of backGrounedWorker
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.WorkerSupportsCancellation = True
BackgroundWorker1.CancelAsync()
Try
BackgroundWorker1.RunWorkerAsync()
Catch ex As Exception
End Try
End Sub
'Here your backGroundProcess
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim FILE_NAME As String
FILE_NAME = txtFileName.Text 'can be changed
Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
Dim Location As String = "C:\MyData\Folder1" 'can be changed
Dim moveToFolder As String = "C:\MyData\Folder2" 'can be changed
Dim fCount As Integer = 0
For Each fileName In fileNames
Dim paths = IO.Directory.GetFiles(Location, fileName,
IO.SearchOption.AllDirectories)
If paths.Count > 0 Then
Try
System.IO.File.Copy(paths(0), moveToFolder & "\" & fileName, True)
Catch ex As Exception
Debug.Print(ex.Message)
End Try
End If
For a = 1 To 100
Debug.Print(a.ToString)
Next
'If any request pending process will be stop (when Button1_click happen while process running (BackGroundWorker in Action))
If BackgroundWorker1.CancellationPending = True Then Exit For
fCount += 1
Dim Progress As Integer = Convert.ToInt32(fCount * 100 / fileNames.Count)
BackgroundWorker1.ReportProgress(progress)
Next
End Sub
'This will show you the progress in your progress bar
Private Sub bw1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Me.ProgressBar1.Value = e.ProgressPercentage
End Sub
'Your Process Have Been Complete Here
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MessageBox.Show("Finish")
End Sub
This last modification from me:
ListBox1.Items.Clear()
Dim FILE_NAME As String
FILE_NAME = "c:\YourFolder\YourFile.txt" 'can be changed
Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
For Each MyFile In fileNames
ListBox1.Items.Add(MyFile)
Next
Dim Location As String = "C:\YourFolder1" 'can be changed
Dim moveToFolder As String = "C:\YourFolder2" 'can be changed
Dim fCount As Integer = 0
For Each fileName In fileNames
Dim paths = IO.Directory.GetFiles(Location, fileName,
IO.SearchOption.AllDirectories)
If paths.Count > 0 Then
Try
System.IO.File.Copy(paths(0), fileName)
Catch ex As Exception
End Try
End If
fCount += 1
Dim progress As Integer = Convert.ToInt32(fCount * 100 / fileNames.Count)
Next

Find REGEX in every file in a folder

I need to evaluate each file in a folder for the ICN string. Then add each ICN to an output file. I found the code below and have made changes to it to meet my needs but it only adds one found file in the ICN.log instead of looping through all files.
Private Sub btnFindICN_Click(sender As Object, e As EventArgs) Handles btnFindICN.Click
Dim Regex = New Regex("[<][!]ENTITY (ICN.*?)[.]\w+")
Dim output = New List(Of String)
Dim tLoc = txtFolderPath.Text
Dim txtFiles = Directory.EnumerateFiles(tLoc, "*.xml", SearchOption.AllDirectories)
For Each tFile In txtFiles
Dim input = File.ReadAllText(tFile)
If Regex.IsMatch(input) Then
Console.Write("REGEX found in " + tFile)
output.Add(tFile)
Exit For
End If
Next
File.WriteAllLines(tLoc.TrimEnd("\"c) & "\ICN.log", output)
End Sub
After I removed the for exit for the code works.
Private Sub btnFindICN_Click(sender As Object, e As EventArgs) Handles btnFindICN.Click
Dim Regex = New Regex("[<][!]ENTITY (ICN.*?)[.]\w+")
Dim output = New List(Of String)
Dim tLoc = txtFolderPath.Text
Dim txtFiles = Directory.EnumerateFiles(tLoc, "*.xml", SearchOption.AllDirectories)
For Each tFile In txtFiles
'MsgBox(tFile)
Dim input = File.ReadAllText(tFile)
If Regex.IsMatch(input) Then
Console.Write("REGEX found in " + tFile)
output.Add(tFile)
'Exit For
End If
Next
File.WriteAllLines(tLoc.TrimEnd("\"c) & "\ICN.log", output)
MsgBox("Function Complete")
End Sub

Download a selected file from my GridView using DoubleClick

I am trying to download a file that I uploaded into my GridView. Each time I double click on the second document in the GridView, it opens the first uploaded document and saves it
Here is my code:
Private Sub dgDocuments_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs)
Handles dgDocuments.DoubleClick
LoadUploadedDocuments()
Try
Dim objTransactionDocument As Objects.TransactionsDocuments
If dgDocuments.CurrentRowIndex.Equals(-1) Then
Dim obj As Object = dgDocuments.Item(dgDocuments.CurrentRowIndex, 1)
objTransactionDocument = Managers.TransactionsDocuments.SelectTransactionsDocuments(Convert.ToInt32(obj))
End If
If Not objTransactionDocument Is Nothing Then
If objTransactionDocument.TransactionsDocumentsID = 1 Then
Dim saveFile As New SaveFileDialog
saveFile.FileName = objTransactionDocument.FileLocation.Substring(objTransactionDocument.FileLocation.LastIndexOf("\"))
saveFile.Title = "Download supporting document to transaction " + m_objTransaction.TransactionID.ToString()
If saveFile.ShowDialog() = DialogResult.OK Then
Dim saveDir As String = Path.GetDirectoryName(saveFile.FileName)
Dim name As String = objTransactionDocument.FileLocation.Substring(objTransactionDocument.FileLocation.LastIndexOf("\"))
Dim saveLocation As String = saveDir + name
System.IO.File.Copy(objTransactionDocument.FileLocation, saveLocation)
MessageBox.Show("Document saved successfully")
End If
End If
End If
Catch ex As Exception
MessageBox.Show("Document saved unsuccessfully " + ex.ToString())
End Try
End Sub
What am I doing wrong?
add / to saveDir as
saveDir+='/'

VB2010 read a csv in datagrid, update in grid and save to same csv

Created a procedure in VB2010 to read a csv-file in datagridviewer, update cells in grid and save to same csvfile
Opening the csvfile in the datagridviewer works fine,
Updating in the datagridviewer works fine also
But when I save the datagrid to a csv-file with the same name, I get an error message "The process Can not access the file because it is used by an other process".
But if I save it to an other filename it is ok.
Then I tried to copy the new file with the new filename back to the original filename.
I received still the same error message that I cant copy because the file is still in use.
Does anybody now how to solve this.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "H:\Data\2014\Software\VB2010\"
OpenFileDialog1.Filter = "CSV files (*.csv)|*.CSV"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
Me.TextBox1.Text = fName
Dim TextLine As String = ""
Dim SplitLine() As String
DataGridView1.ColumnCount = 5
DataGridView1.Columns(0).Name = "Name"
DataGridView1.Columns(1).Name = "Gender"
DataGridView1.Columns(2).Name = "Age"
DataGridView1.Columns(3).Name = "Ranking"
DataGridView1.Columns(4).Name = "Date"
If System.IO.File.Exists(fName) = True Then
Dim objReader As New System.IO.StreamReader(fName)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ",")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
Else
MsgBox("File Does Not Exist")
End If
End Sub
Private Sub SaveGridDataInFile(ByRef fName As String)
'method called by button2
Dim I As Integer = 0
Dim j As Integer = 0
Dim cellvalue$
Dim rowLine As String = ""
Try
Dim objWriter As New System.IO.StreamWriter(fName, True)
For j = 0 To (DataGridView1.Rows.Count - 2)
For I = 0 To (DataGridView1.Columns.Count - 1)
If Not TypeOf DataGridView1.CurrentRow.Cells.Item(I).Value Is DBNull Then
cellvalue = DataGridView1.Item(I, j).Value
Else
cellvalue = ""
End If
rowLine = rowLine + cellvalue + ","
Next
objWriter.WriteLine(rowLine)
rowLine = ""
Next
objWriter.Close()
objWriter = Nothing
MsgBox("Text written to file")
Catch e As Exception
MessageBox.Show("Error occured while writing to the file." + e.ToString())
Finally
FileClose(1)
End Try
Call copy_file()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'çall method SaveGridDataInFile
SaveGridDataInFile(Me.TextBox1.Text)
' FileCopy("H:\Data\2014\Software\VB2010\datagr_ex2.csv", "H:\Data\2014\Software\VB2010\datagr_ex.csv")
End Sub
Sub copy_file()
Dim FileToDelete As String
FileToDelete = "H:\Data\2014\Software\VB2010\datagr_ex.csv"
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
MsgBox("File Deleted")
End If
FileCopy("H:\Data\2014\Software\VB2010\datagr_ex2.csv", "H:\Data\2014\Software\VB2010\datagr_ex.csv")
End Sub
My guess is you need to close the StreamReader you use to load the file before you can reopen the file to save it. The StreamReader class implements IDisposable so you can use VB.Net's Using Statement to automatically close the file when you're finished reading, i.e.
If System.IO.File.Exists(fName) = True Then
Using objReader As New System.IO.StreamReader(fName)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ",")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
End Using
Else
MsgBox("File Does Not Exist")
End If

vb.net appendline substring error

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