I'm trying to get a file and iterate through it using StreamReader and load each line into an array. I know the file is coming in correctly and it is a text file of data coming in lines.
Dim req As WebRequest = WebRequest.Create("http://www.blahahahaha.com/data/myfile.csv")
Dim res As WebResponse = req.GetResponse()
Dim stream As Stream = res.GetResponseStream()
Dim lines2 As String()
Using r As StreamReader = New StreamReader(stream, Encoding.ASCII)
Dim line As String
line = r.ReadLine
Do While (Not line Is Nothing)
lines2(lineCount2) = r.ReadLine
lineCount2 += 1
Loop
End Using
But the resulting array is empty. What am I doing wrong and how do I fix it?
This line:
Dim lines2 As String()
Just declares that lines2 will be a string array. The array itself is not intialized:
Dim lines2(9) As String ' THIS one has elements
But since you likely do not know how many lines there will be, use a List:
Dim Lines As New List(Of String)
Using r As StreamReader = New StreamReader(Stream, Encoding.ASCII)
Dim line As String
line = r.ReadLine
Do Until String.IsNullOrEmpty(line)
Lines.Add(line)
line = r.ReadLine
Loop
End Using
If the calling code really needs an array:
Return Lines.ToArray()
This will return 6 lines as a string array, first line is column names
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim csvAddress As String =
"https://download.microsoft.com/download/4/C/8/4C830C0C-101F-4BF2-8FCB-32D9A8BA906A/Import_User_Sample_en.csv"
Dim Lines As String() = GetCsvData(csvAddress)
For Each line As String In Lines
Console.WriteLine(line)
Next
End Sub
Public Function GetCsvData(ByVal csvAddress As String) As String()
Dim request As WebRequest = WebRequest.Create(csvAddress)
request.Credentials = CredentialCache.DefaultCredentials
Dim response As WebResponse = request.GetResponse()
Dim dataStream As Stream = response.GetResponseStream()
Dim LineList As New List(Of String)
Using r As StreamReader = New StreamReader(dataStream, Encoding.ASCII)
Dim currentLine As String = r.ReadLine
Do While (Not String.IsNullOrWhiteSpace(currentLine))
LineList.Add(currentLine)
currentLine = r.ReadLine
Loop
End Using
Return LineList.ToArray
End Function
Related
I have a bunch of csv files in a folder. Here is a sample:
Item Value
Row1 Val1
Row2 Val2
Row3 Val3
Row4 Val4"
Row5 Val5
I had written a code to plot a chart based on the information available in all the csv file in that folder. Here is my button click event:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles generatePlot.Click
Dim dirs As FileInfo() = GetFilesInDirectory("*.csv", True) 'Get all the csv file from result folder in descending order (creation date)
Dim diNext As FileInfo
Try
For Each diNext In dirs.Reverse
Using MyReader As New FileIO.TextFieldParser(diNext.FullName)
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
currentRow = MyReader.ReadFields()
processRow(diNext, currentRow)
End While
End Using
Next
Catch ex As Exception
MessageBox.Show(ErrorToString)
End Try
'Save chart as an image
Chart1.SaveImage(imageSave, System.Drawing.Imaging.ImageFormat.Bmp)
End Sub
If you look at my sample csv, Row4 has a value of Val4". Note the double quote in it. And, I am getting an exception in my code at currentRow = MyReader.ReadFields() which says Line 5 cannot be parsed using the current delimiter. I know that the reason is because of the presence of double quote. Since this is a string array, I thought that I need to create a function to process each item in the array and trim out the double quote. But, I can't do it as the exception is thrown even before I can process the string array.
Any idea on how to solve this?
Hari
A StreamReader can be used to read text files, just look at the example below to achieve your needs:
Note that the MemoryStream and the Writer are not needed for you, just the Reader.
Public Sub ReadTest()
Using MemoryStream As New IO.MemoryStream()
Dim Writer As New IO.StreamWriter(MemoryStream) 'Writing on a memory stream to emulate a File
Writer.WriteLine("Item,Value")
Writer.WriteLine("Row1,Val1")
Writer.WriteLine("Row2,Val2")
Writer.WriteLine("Row3,Val3")
Writer.WriteLine("Row4,Val4""")
Writer.WriteLine("Row5,Val5")
Writer.Flush()
MemoryStream.Position = 0 'Reseting the MemoryStream to Begin Reading
Dim Reader As New IO.StreamReader(MemoryStream) 'Reading from the Memory but can be changed into the File Path
While Not Reader.EndOfStream
Dim Line As String = Reader.ReadLine
Dim Values() = Line.Split(",")
'Values(0) will contain the First Item
'Values(1) will contain the second Item
Values(1).Replace("""", "") 'Remove the quote from the value string
End While
End Using
End Sub
Thanks to the suggestion given by #jmcilhinney and #AugustoQ.
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles generatePlot.Click
Dim dirs As FileInfo() = GetFilesInDirectory("*.csv", True) 'Get all the csv file from result folder in descending order (creation date)
Dim diNext As FileInfo
Dim currentRow As String()
Try
For Each diNext In dirs.Reverse
For Each rawRows As String In File.ReadLines(diNext.FullName)
currentRow = processRawRow(rawRows)
processRow(diNext, currentRow)
Next
Next
Catch ex As Exception
MessageBox.Show(ErrorToString)
End Try
'Save chart as an image
Chart1.SaveImage(imageSave, System.Drawing.Imaging.ImageFormat.Bmp)
End Sub
I had replaced the TextFieldParser completely and used this function:
Private Function processRawRow(ByVal rawRows As String) As String()
rawRows = rawRows.Replace("""", "").Trim()
Dim processedList = rawRows.Split(",")
Return processedList
End Function
And it works perfectly. Thanks everyone...
Hari
I have this code written in Visual basic:
Dim directory As String = Application.StartupPath()
Dim dirinfo As New DirectoryInfo(directory)
Dim filesnatt As String() = dirinfo.GetFiles("*.nat")
Dim filenatt As String
For Each filenatt In filesnatt
Dim filenat As String = Str(filenatt)
Using re As StreamReader = New StreamReader(filenat)
Dim val As String = re.ReadLine()
If val.Contains(TextBox2.Text) Then
Dim a1 As String = filenat
a1 = a1.Remove(".nat")
ComboBox2.Items.Add(a1)
End If
End Using
Next
But I get this error: Value of '1 - dimensional array of System.IO.FileInfo' cannot be converted to '1 - dimensional array of String' because 'System.IO.FileInfo' is not derived from 'String'.
How to fix that?
thats because GetFiles returns FileInfo instead of String change
Dim filesnatt as String() to Dim filesnatt as FileInfo()
and
Dim filenatt as String to Dim filenatt as FileInfo
and in the For Each loop use
Dim filenat as String = filenatt.FullName
I'm trying to replace all double quotes in a file but when I try to update the string array I just get the original line again instead of the cleaned string. (The Boolean's in the ReplaceQuotes function are just for testing and they come back true when there's a " in the line). If I look at the cleanLine string, the quotes have been removed, but when I return the fileContent array, it looks just like the original with the quotes.
Private Sub CleanFile(currentFileInfo As FileInfo)
Dim fullName As String = currentFileInfo.FullName
Dim fileContent As String() = GetFileContent(currentFileInfo.FullName)
Dim cleanFileContent As String() = ReplaceQuotes(fileContent)
End Sub
Private Function GetFileContent(fileName As String) As String()
Return System.IO.File.ReadAllLines(fileName)
End Function
Private Function ReplaceQuotes(fileContent As String())
For Each line As String In fileContent
Dim cleanLine As String
Dim quoteTest As Boolean
quoteTest = line.Contains("""")
Dim quoteTest2 As Boolean = line.Contains(ControlChars.Quote)
cleanLine = line.Replace(ControlChars.Quote, "")
line = cleanLine
Next
Return fileContent
End Function
You have to re-assign the new strings in the original array instead of replacing the local string variables. Therefore you can't use a For Each but only a For-loop. And the method can be shorter:
Private Sub ReplaceQuotes(fileContent As String())
For i As Int32 = 0 To fileContent.Length - 1
fileContent(i) = fileContent(i).Replace(ControlChars.Quote, "")
Next
End Sub
This question already has answers here:
Variable has been used before it has been assigned a value
(3 answers)
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I am trying to fill an array using a loop in VB. It basically read a .txt file and store all the line in an array. Im getting this error. "Array is used before it has been assigned values".
Dim fileEntries As String() = Directory.GetFiles(folderDIR, "*.txt")
Dim fileName As String
Dim fileReader As StreamReader
Dim strReadFile As String
Dim arrLines() As String
Dim i As Integer = 0
For Each fileName In fileEntries
fileReader = File.OpenText(fileName)
Do Until fileReader.Peek = -1
strReadFile = fileReader.ReadLine()
arrLines(i) = strReadFile
i += 1
Loop
Next
Is there any way I could do this, without pre-defining length of the array? I want the length of array to be number of lines in txt files. Hope i explained this well. Thank you in advance.
You can do something like this:
Dim fileEntries As String() = Directory.GetFiles(folderDIR, "*.txt")
Dim fileName As String
Dim fileReader As StreamReader
Dim strReadFile As String
Dim arrLines() As String = {} 'Added this
'Dim i As Integer = 0 'Removed this
For Each fileName In fileEntries
fileReader = File.OpenText(fileName)
Do Until fileReader.Peek = -1
strReadFile = fileReader.ReadLine()
If arrLines.Length = 0 Then ReDim arrLines(0 To 0) Else ReDim Preserve arrLines(0 To arrLines.Length)
arrLines(arrLines.Length - 1) = strReadFile
i += 1
Loop
Next
Or so...
There is quite a while, in vb6, I used ReDim to dynamically add a new entry in the array in the loop.
Inconvenient: slow down the process.
Better to count the occurrences needed from the file before creating the array.
Hope that helps.
you can declare arrlines as list:
Dim arrLines As New List(Of String)()
then you can convert to arrLines to array :
arrLines.ToArray()
try this:
Dim fileEntries As String() = Directory.GetFiles(folderDIR, "*.txt")
Dim fileName As String
Dim fileReader As StreamReader
Dim strReadFile As String
Dim arrLines As New List(Of String)()
Dim i As Integer = 0
For Each fileName In fileEntries
fileReader = File.OpenText(fileName)
Do Until fileReader.Peek = -1
strReadFile = fileReader.ReadLine()
arrLines.Add(strReadFile)
Loop
Next
arrLines.ToArray()
I have a text file like:
[edit] the number of line is unknown, it could be hundreds of lines.
How would I store them in a multidimensional array? I want my array to look like:
sample(0)(0) = "--------"
sample(0)(1) = "Line1"
..and so on
sample(1)(0) = "--------"
sample(1)(3) = "Sample 123"
..and so on
What I have done so far was to open the file and store in a 1-dimentional array:
logs = File.ReadAllLines("D:\LOGS.TXT")
I have tried creating an Array of string like:
Dim stringArray as String()()
stringArray = New String(varNumber0)(varNumber1)
But it returns and error.
You can use File.ReadLines/File.ReadAllLines to get the lines and a simple For Each-loop to fill a List(Of List(Of String)). Then you can use
list.Select(Function(l) l.ToArray()).ToArray()
to get the String()() (jagged array):
Dim lines = File.ReadLines("D:\LOGS.TXT")
Dim list As New List(Of List(Of String))
Dim current As List(Of String)
For Each line As String In lines.SkipWhile(Function(l) Not l.TrimStart.StartsWith("----------"))
If line.TrimStart.StartsWith("----------") Then
current = New List(Of String)
list.Add(current)
Else
current.Add(line)
End If
Next
Dim last = list.LastOrDefault()
If last IsNot Nothing Then
If Not current Is last AndAlso current.Any() Then
list.Add(current)
ElseIf Not last.Any() Then
list.Remove(last) ' last line was ("----------")'
End If
End If
Dim stringArray As String()() = list.Select(Function(l) l.ToArray()).ToArray()
If you want to include the --------- in the array at the first position:
For Each line As String In lines.SkipWhile(Function(l) Not l.TrimStart.StartsWith("----------"))
If line.TrimStart.StartsWith("----------") Then
current = New List(Of String)
current.Add(line)
list.Add(current)
Else
current.Add(line)
End If
Next
Try like this but you need to customize according to you
Dim mArray(10,10) As String
Dim i As Integer = 0
For I=0 to 10
For J=0 to 10
For Each line As String In System.IO.File.ReadAllLines("file.txt")
mArray(i,j) = cmdReader.Item(line)
Next
Next
Next
Use declaration like this (this is just a generic)
Dim dim1 As Integer = 0
Dim dim2 As Integer = 0
Dim strings(,) As String
Do
dim1 = NewDimensionNumberFromFile
dim2 = NewSecondDimensionNumberFromFile
ReDim Preserve strings(dim1, dim2)
strings(dim1, dim2) = ValueFromfile
Loop While (Not EOF()) 'this will determine