String array replace not updating original string - arrays

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

Related

Storing variables generated by a while loop

I have a while loop that parses a csv file, and inserts the variables into a series of arrays. This is called by a button on my main form.
These variables are used for a chart (which is in the same sub) and also for a datagrid, which is on a separate form.
The first time I click the button, everything works as normal, however if I click it a second time, the datagrid on the separate form is not populated, as I am losing the variables.
So within the while loop which parses the CSV file, I have this:
frmNumericChart.DataGridView1.Rows.Add(freq, dBu, dbnorm, ScaleFactor)
I have tried making the variables public, however because they are arrays, and constructed from the while loop, I can't seem to make them publicly accessible.
My code (edited for brevity)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sFile As String = strFileName
' get the minimum and maximum frequencies
Dim Lines As Collections.Generic.IEnumerable(Of String) = File.ReadLines(strFileName)
Dim Line0 As String = Lines.FirstOrDefault
Dim LineN As String = Lines.LastOrDefault
Dim lowestFreq As String() = Line0.Split(New Char() {","c})
Dim highestFreq As String() = LineN.Split(New Char() {","c})
Dim lowFreq As String = lowestFreq(0)
Dim highFreq As String = highestFreq(0)
Dim refFrequencyX = Lines(18)
Dim refFreq As String() = refFrequencyX.Split(New Char() {","c})
Dim ScaleFactor As String = refFreq(1)
Using sr As New StreamReader(sFile)
While Not sr.EndOfStream
Dim sLine As String = sr.ReadLine()
If Not String.IsNullOrWhiteSpace(sLine) Then
sData = sLine.Split(","c)
arrName.Add(sData(0).Trim())
arrValue.Add(sData(1).Trim())
End If
Dim freq As Decimal = sData(0)
Dim dBu As Decimal = sData(1)
Dim voltage As Decimal = sData(1)
' dbnorm - normalise output to 0dBu ref 1kHz
Dim dbnorm = Math.Round(dBu - ScaleFactor, 4)
frmNumericChart.DataGridView1.Rows.Add(freq, dBu, dbnorm, ScaleFactor)
Chart1.Series(0).Points.AddXY(freq, dbnorm)
End While
End Using
' ( chart is constructed here )
end sub
How can I make these array variables global?
Please excuse my shoddy code - I am doing this as a hobby and learning as I go along.
I solved this by adding a public class into a module.
Inside the 'Public Class' I have 'Public Shared Sub' for the subs I want access to from anywhere within the code.
Example:
Public Module Module1
<various public variables here>
Public Class MyData
Public Shared Sub debugTempFile()
' DEBUG
Dim mytempFolder As String = Path.GetTempPath()
Dim MyOutFile As String = mytempFolder + "outfile.txt"
Dim myfile As System.IO.StreamWriter
myfile = My.Computer.FileSystem.OpenTextFileWriter(MyOutFile, True)
myfile.WriteLine(debugdata)
myfile.Close()
' END DEBUG
End Sub
End Class
End Module
This Public Sub can be called from anywhere using the call statement:
Call MyData.debugTempFile()
I hope this is of use to other beginners like myself.

element of array to string in Visual Basic

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

Loading file into array using streamreader

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

"System.NullReferenceException" while filling dictionary with keys from an array

I have a problem in my code. here is the problematic snippet. The reading of the line does work, but at the point where he should fill the zeilendict with the keys and the values, he throws an "System.NullReferenceException" and I dont know why.
Did I do something wrong in the loop, or is the dictionary not right iniziated? or is arr1 empty?
Module Module1
Public zeilendict As Dictionary(Of String, Integer)
Public insertdict As Dictionary(Of String, String)
Public Sub einlesen()
Form1.ID = 0
Form1.OpenFileDialog1.ShowDialog()
Form1.path = Form1.OpenFileDialog1.FileName
Form1.OpenFileDialog1.Dispose()
Dim fs As FileStream = New FileStream(Form1.path, FileMode.Open, FileAccess.Read)
Dim sr As StreamReader = New StreamReader(fs)
Dim ersteZeile = sr.ReadLine()
Form1.arr1 = ersteZeile.Split(New Char() {";"c})
sr.Close()
fs.Close()
Dim i As Integer
For i = 0 To Form1.arr1.Length - 1
Form1.DataGridView1.Rows.Add(Form1.arr1(i))
Next
Dim i1 As Integer
For i1 = 0 To Form1.arr1.Length - 1
zeilendict.Add(Form1.arr1(i1), 0)
Next
It seems you have not initiated your dictionary. There for adding items will give a NullRefException
Try adding:
Public zeilendict As Dictionary(Of String, Integer) = new Dictionary(Of String, Integer)()
or set this as first line in your method:
zeilendict = new Dictionary(Of String, Integer)()
Also do this for the other Dictionary
Add the keyword "New" to your declartion to initialize your dictionary:
Public zeilendict As New Dictionary(Of String, Integer)
Otherwise it will only be declared but contain nothing, therefore the Exception when you try to add something.
More information: http://msdn.microsoft.com/en-us/library/7zc73115%28v=vs.90%29.aspx

multidimentional array of strings in vb.net

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

Resources