Is it possible to Dim a variable in VB.net using values from an array? - vb.net

I need to create several text files in vb.net based on values entered in a spreadsheet. Each text file will be named 'valuename.txt'.
I populate an array with the value names as they are entered:
issues(j) = Grid1.Cells(1, j).Value
Now I need to open text files with their names. I would like to do something along the lines of:
Dim Filename As String = "C:\" & Grid1.Cells(1, j).Value & ".txt"
Dim issues(j) As New System.IO.StreamWriter(Filename)
When I enter this in Visual Studio, it says it does not like:
issues(j)
Do I have any other options?

It seems like the code you have posted is inside a for loop with j being the counting variable.
You are already building a filename from the cell values, so just declare the streamwriter as a new variable and use it:
For j = 0 To Grid1.Rows.Count - 1 'Assumed by me
'Create the filename for the current row
Dim Filename As String = "C:\" & Grid1.Cells(1, j).Value & ".txt"
'The Using block makes sure that the ressources used by the streamwriter are disposed again.
'It is equivalent as Dim sw As New IO.Streamwriter, but Using should be preferred
Using sw As New IO.StreamWriter(Filename)
'Use the streamwriter to write the data
End Using
'If you additionally want to store the values in an array for whatever reason
issues(j) = Grid1.Cells(1, j).Value
Next
Your Dim issues(j) statement does not make any sense.
To append data to an existing file, use the overload of the StreamWriter constructor:
Using sw As New IO.StreamWriter(Filename, True)
The second parameter defines if data should be added to the file.

You can use Using to declare a new StreamWriter:
Dim Filename As String = "C:\" & Grid1.Cells(1, j).Value & ".txt"
Using fsw As New System.IO.StreamWriter(Filename)
'Do Something
End Using
But if you insist to use a list of StreamWriter (I don't know why) then you can do something like this:
Dim fsw As New List(Of System.IO.StreamWriter)
fsw(j) = New System.IO.StreamWriter(Filename)
'Do Something
fsw(j).Close
fsw(j).Dispose

Related

VB.net: overwrite everything in a text file

in my VB.net Application id like to overwrite and add new content of a text file
What Code do I need to use?
Thanks
Read (ie: load) everything in the TXT file into your program.
Dim sFullPathToFile As String = Application.StartupPath & "\Sample.txt"
Dim sAllText As String = ""
Using xStreamReader As StreamReader = New StreamReader(sFullPathToFile)
sAllText = xStreamReader.ReadToEnd
End Using
Dim arNames As String() = Split(sAllText, vbCrLf)
'Just for fun, display the found entries in a ListBox
For iNum As Integer = 0 To UBound(arNames)
If arNames(iNum) > "" Then lstPeople.Items.Add(arNames(iNum))
Next iNum
Because you wanted to overwrite everything in the file, we now use StreamWriter (not a StreamReader like before).
'Use the True to indicate it is to be appended to existing file
'Or use False to open the file in Overwrite mode
Dim xStreamWRITER As StreamWriter = New StreamWriter(sFullPathToFile, False)
'Use the carriage return character or else each entry is on the same line
xStreamWRITER.Write("I have overwritten everything!" & vbCrLf)
xStreamWRITER.Close()

Dynamically edit Contents of a CSV file using VB.net

I have this code
Dim fileReader As System.IO.StreamReader
fileReader =
My.Computer.FileSystem.OpenTextFileReader("Filepath")
Dim stringReader As String
'read csv file from first to last line
While fileReader.ReadLine <> ""
'get data of line
stringReader = fileReader.ReadLine()
'check the number of commas in the line
Dim meh As String() = stringReader.Split(",")
If meh.Length > 14 Then
My.Computer.FileSystem.WriteAllText("Filepath", "asd", True)
ElseIf meh.Length < 14 Then
My.Computer.FileSystem.WriteAllText("Filepath", "asd", True)
ElseIf meh.Length = 14 Then
MsgBox("This line of the file has " & stringReader & meh.Length & "commas")
End If
End While
End
End Sub
To explain, the above code would check EACH line of a CSV file to check weather the contents has 14 commas('). Then if that line has more commas, the code will reduce it to 14, and if not, it would write commas so that it would be equal to 14. The above conditions are not created yet, so the code is just for testing. I read something about WriteAllText and this code gives me the error :
The process cannot access the file 'filepath' because it is being used by another process.
Which, I think, means that I cant edit the CSV file because I'm currently using its data.
My question is, how could I edit the contents of the CSV file even when I am checking its contents?
Please do disregard this code
My.Computer.FileSystem.WriteAllText("Filepath", "asd", True)
as I use this code just for testing, if ever I could manage to write it to the CSV file.
I Thank you for all your help.
If your CSV is not too big, you can read it in memory and work with it. When you have finish you can write it again on disk.
'Declare 2 List (or you can work directly with one)
Dim ListLines As New List(Of String)
Dim ListLinesNEW As New List(Of String)
'Read the file
Using MyCSVread As New IO.FileStream("C:\MyCSV.csv", IO.FileMode.Open, IO.FileAccess.ReadWrite)
'Read all the lines and put it in a list of T (string)
Using sReader As IO.StreamReader = New IO.StreamReader(MyCSVread)
Do While sReader.Peek >= 0
ListLines.Add(sReader.ReadLine)
Loop
End Using
End Using
'Your code for work with the line. Here you can write the new lines in the NEW list of string or work directly in the first
For L As Integer = 0 To ListLines.Count - 1
Dim meh As String() = ListLines(L).Split(",")
If meh.Length > 14 Then
'your code ...
ElseIf meh.Length < 14 Then
'your code ...
ElseIf meh.Length = 14 Then
MessageBox.Show("The line " & (ListLines(L) + 1) & " of the file has " & meh.Length & "commas", "MyApp", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
Next
'Open again the file for write
Using MyCSVwrite As New IO.FileStream("C:\MyCSV.csv", IO.FileMode.Open, IO.FileAccess.ReadWrite)
'Write back the file with the new lines
Using sWriter As IO.StreamWriter = New IO.StreamWriter(MyCSVwrite)
For Each sLine In ListLinesNEW.ToArray
sWriter.WriteLine(sLine)
Next
End Using
End Using
The "Using" auto close the filestream or a streamreader/write or what you use. Then you will not have problem like "file already in use".
Hope this help.

Using an array to search a file VB

I have a program that needs to look through a text file line by line, the lines look like this:
10-19-2015 Brett Reinhard All Bike Yoga Run the Studio Design Your Own Strength
These are separated by tabs in the text file.
What I want to do is look at the second value, in this case "Brett Reinhard" and move the full line to another textfile called "Brett Reinhard"
I was thinking of using an array to check to see if the second 'column' in the line matched any value within a given array, if it does I want to perform a specific action.
The way I am thinking of doing this is with a For/next statement, now while it will work it will be a laborious process for the computer that I will be using it on.
The code I am thinking of using looks like this:
For intCounter=0 to Whatever Number is the last number of the array
If currentfield.contains(array(intCounter)) Then
Open StreamWriter(File directory & array(intcounter) & ".txt")
Streamwriter.Writeline(currentfield)
End IF
Is there a better way of doing this, such as referencing the second 'column' in the line, similar to the syntax used in VBA for excel.
Name=Cells(1,2).Value
If you can guarantee that a line will only use the tab characters as field separators, you can do something along this:
Open the stream for reading text
Open a stream for writing text
Read a line of text
Use the Split method to break the incoming line into an array of fields
If the second element in the array is your sentinel value, write the original line to the writer
Repeat yourself until you have reached the end of file (ReadLine will return Nothing, or null for those c# folk).
Close and dispose of your stream objects.
If you aren't sure of the format, you will want to take the hit and use the TextFieldParser as mentioned in an earlier comment.
So while its not using an array to search a file, what I ended up doing works just as well. I ended up using the split method thanks to #Martin Soles.
Here is what I came up with:
Sub Main()
Dim intCount As Integer = 1
Dim words As String
Dim split As String()
Using MyReader As New Microsoft.VisualBasic.
FileIO.TextFieldParser(
"I:\Games, Events, & Promotions\FRP\Back End\Approved.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
words = currentField
split = words.Split(New [Char]() {CChar(vbTab)})
For Each s As String In split
If intCount = 2 Then
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("I:\Games, Events, & Promotions\FRP\Back End\" & s & ".txt", True)
file.WriteLine(currentField)
file.Close()
End If
intCount = intCount + 1
Next s
intCount = 1
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using
End Sub 'Main
Thank you guys for the suggestions.
For right now the split method will work for what is needed.

Visual Basic Append to a specific point in a text file

I am currently trying to manipulate a line in a file that we are using to retain data, using comma delimiters. For example -
121,1212, XJAY,Sean K,Kean S,AAAA-BBBB-AAAA-BBBB-AAAA
12456,987654,WYST,Steve Jobs,Bill Gates,CAAA-BBBB-AAAA-BBBB-AAAA
If I assume that the last line is always a unique code, is it possible to identify that line in the text file and append it with another field?
Prior research has been reading through the APIs for StreamReader and StreamWriter, and looking through other StackOverflow questions, however most questions seem focused on just appending to the end of the file, or in different languages!
As always thank you for your time, and if there is anything I've left off please let me know!
You can't manipulate a line in a file in any reasonably easy way.
There are no methods to work with lines in a file, because files are not line based. They are not even character based. The bytes in the file are decoded into characters, then the line break characters are recognised and the characters can be split into lines.
The easiest way to manipulate a line is to read the entire file into a string array, change the string that you want change, then write the entire string array to the file.
Example:
Dim fileName As String = "c:\data.txt"
Dim lines As String() = File.ReadAllLines(fileName)
For i As Integer = 0 To lines.Length - 1
Dim line As String = lines(i)
If line.StartsWith("12456,") Then
lines(i) = line & ",More data"
End If
Next
File.WriteAllLines(fileName, lines)
If you are looking for a way to parse Each line with StreamReader and StreamWriter: Here it is:
'You will need Imports System.IO
Dim TheNewFile As String
Dim MyLine As String
Dim MyStream2 As New FileStream("C:\Your Directory\YourFile.txt", FileMode.Open)
Dim MyReader As New StreamReader(MyStream2)
Dim MySettings As New StringReader(MyReader.ReadToEnd)
MyReader.BaseStream.Seek(0, SeekOrigin.Begin)
MyReader.Close()
MyStream2.Close()
Try
Do
MyLine = MySettings.ReadLine
'This if statement is an exit parameter. It can be if it contains or if 5 consecutive lines are nothing. It could be a number of things
If MyLine Is Nothing Then Exit Do
'This is the file you will write. You could do if MyLine = "Test" Then ........... append whatever and however you need to
TheNewFile = TheNewFile & MyLine & vbCrLf
Loop
Catch ex As Exception
MsgBox(ex.ToString())
End Try
'-----------------Write The new file!!!----------------
Dim MyStream3 As New FileStream("C:\Where you want to write New File\NewFileName.txt", FileMode.Create)
Dim MyWriter3 As New StreamWriter(MyStream3)
MyWriter3.Write(TheNewFile & "Test")
MyWriter3.Close()
MyStream3.Close()

My visual basic program is creating files improperly and they won't run correctly through other programs

I have a visual basic program that creates files that are necessary for a semiweekly process. These files are a .bas file (for qbasic) and a .lot file (for voxco automation). I can live without the .bas file and simply put it's functionality directly into my program. I do, however, need the .lot file. Normally these files are copied from old files and edited manually. This is, as you can imagine, tedious. However, the files created by my program do not run properly through any means I have of running them. When I compare the manually created files to the automatically created files, the differences are minimal to nonexistent. The encoding doesn't seem to be an issue either. I simply don't know why the files created by my program are not running properly when the files created manually are working fine.
Here is the code that creates the .lot file:
Dim LotText As String
LotText = *removed*
Dim QuLines As String = Nothing
Dim Reader As New StreamReader(LotFilePath & OldStudy & ".LOT")
Dim SLine As String = Nothing
While Not Reader.EndOfStream
SLine = Reader.ReadLine()
If SLine.StartsWith("*QU") Then
QuLines = QuLines & SLine & vbCrLf
End If
End While
LotText = LotText & QuLines
Dim TempPath As String
TempPath = LotFilePath & "BackEnd\" & StudyID & ".LOT"
My.Computer.FileSystem.WriteAllText(TempPath, LotText, 0)
When you say the differences are minimal - what are they exactly!? A single character at the beginning of the file could be making the whole thing fail.
I have had problems in the past with writing vbCrLf to files in this manner; try the following code instead to see if it offers any improvement.
Dim LotText As String = *removed*
' Create a list of strings for the output data
Dim QuLines As New Collections.Generic.List(Of String)
Dim Reader As New StreamReader(Path.Combine(LotFilePath, OldStudy & ".LOT"))
Dim SLine As String = Nothing
While Not Reader.EndOfStream
SLine = Reader.ReadLine()
If SLine.StartsWith("*QU") Then
' This line is desired; add it to our output list
QuLines.Add(SLine)
End If
End While
' Concatenate the existing data and the output; uses the system defined NewLine
LotText &= Environment.NewLine & String.Join(Environment.Newline, QuLines)
Dim TempPath As String = Path.Combine(LotFilePath, "BackEnd", StudyID & ".LOT")
My.Computer.FileSystem.WriteAllText(TempPath, LotText, 0)