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
Related
I'm trying to convert a string array to byte array. I would like to use Encoding.Default.GetBytes() but it only accepts String and Char(). This is the code
Dim aStringArray(2) As String
aStringArray(0) = "FileName"
aStringArray(1) = "FileSize"
Dim stringArrayBytes() As Byte = Encoding.Default.GetBytes(aStringArray) `this is wrong
If you are trying to combine the array into a single byte array try this
Dim aStringArray(1) As String
aStringArray(0) = "FileName"
aStringArray(1) = "FileSize"
Dim stringArrayBytes As New List(Of Byte)
For Each s As String In aStringArray
stringArrayBytes.AddRange(System.Text.Encoding.Default.GetBytes(s))
Next
Dim bytarray() As Byte = stringArrayBytes.ToArray
Here little bid different approach, based on your example :)
Dim aStringArray(2) As String
aStringArray(0) = "FileName"
aStringArray(1) = "FileSize"
Dim allStrngItems As String = String.Join(String.Empty, aStringArray)
Dim allBytes As Byte() = Encoding.Default.GetBytes(allStrngItems)
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
I am trying to assign values to the strings in a comma separated string.
See incorrect code below.
Dim newArray As String() = "M2-1_,IR,Pass,499V,>10G,5.0s"
results = Split(newArray, ",", -1, vbBinaryCompare)
Dim results1 As String = newArray(0)
Dim results2 As String = newArray(1)
Dim results3 As String = newArray(2)
ListBox1.Items.Add(results1)
ListBox1.Items.Add(results2)
ListBox1.Items.Add(results3)
My current results are:
M
2
-
I would like the results:
M2-1_
IR
Pass
Thanks!!!!!
If you want just the first 3:
Dim newArray As String = "M2 - 1_,IR,Pass,499V,>10G,5.0s"
ListBox1.Items.AddRange(newArray.Split(",").Take(3).ToArray)
If you want them all:
Dim newArray As String = "M2 - 1_,IR,Pass,499V,>10G,5.0s"
ListBox1.Items.AddRange(newArray.Split(","))
Dim newArray = "M2-1_,IR,Pass,499V,>10G,5.0s"
Dim results() As String = newArray.Split(",")
ListBox1.Items.Add(results1(0))
ListBox1.Items.Add(results2(1))
ListBox1.Items.Add(results3(2))
Your code works if you index into the results array when adding to the ListBox.
Dim newArray As String = "M2-1_,IR,Pass,499V,>10G,5.0s"
Dim results() = Split(newArray, ",", -1, vbBinaryCompare)
ListBox1.Items.Add(results(0))
ListBox1.Items.Add(results(1))
ListBox1.Items.Add(results(2))
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