VB.NET write/read data from text file - vb.net

This might be something that I am overlooking, as I am currently reading a book on VB.NET. I canceled a course in VB.Net recently because I was stuck on a problem and the lecturer did not get back to me with my questions that I had.
The objective was to create a business application with VB.NET that writes data from text boxes to a text file, seperated by a comma or a pipe. The user of the application must be able to select the directory where they want the file to be saved.
So I have for example 2 forms, one that captures the data for a client, and another form where you can select from a drop-down control, Now I know that streamwriter allows for the user to select self where they want the file to be saved, but how do I make the second form intelligent to know where the user saved the form and then reads the client_id, and fills the other data associated with the client_id to the text boxes in the form. I know streamreader is the one to use when you want to read data from a file, but how will streamreader know where the user will save the file to?
I am not doing the course any more, but I will keep on thinking what I could have done to actually get the project to work.

For writing to file
// Write single line to new file.
Using writer As New StreamWriter("C:\log.txt", True)
writer.WriteLine("Important data line 1")
End Using
For reading from file
// read from a file
Dim line As String
Using reader As New StreamReader("file.txt")
line = reader.ReadLine()
End Using
Console.WriteLine(line)

Related

How to Serialize or Save Multiple Forms to Single File

Essentially I'm creating a D&D character sheet with 9 forms, 6 of which will be saved. I need to save every TextBox in each of those 6 forms. I haven't tried Serialization yet as I haven't found an especially good guide that clarifies exactly what I need to do yet, and at this point it's fairly confusing to me. I have, however, tried saving to a file and writing back when the file is opened. This works for one form, but I'm almost certain that it won't work for multiple forms given the way that the code is written.
Dim SaveCharacter As StreamWriter
If txtName.Text = "" Then
MessageBox.Show("In order to save, you must at least enter a name for your character.", "Error: No Name Entered")
Else
SaveCharacterAs.ShowDialog()
System.IO.File.WriteAllText(SaveCharacterAs.FileName, "")
Try
For Each cnt In Me.Controls.OfType(Of TextBox)
SaveCharacter = File.AppendText(SaveCharacterAs.FileName)
SaveCharacter.WriteLine(cnt.Text)
SaveCharacter.Close()
Next
For Each cnt In frmAttributeRoller.Controls.OfType(Of TextBox)
SaveCharacter = File.AppendText(SaveCharacterAs.FileName)
SaveCharacter.WriteLine(cnt.Text)
SaveCharacter.Close()
Next
The above code is what I have for writing to a file. I was thinking of trying to save the file to a .txt file with the name of the character that's entered in the form, and for each subform that I'm saving, create a separate .txt file with the character name concatenated with the form name, then write code to open all of those files in the correct forms, but that could get messy if the user selects the wrong file to start with. Is there a better way to save multiple forms to one file without serializing? Is serializing my best bet?
Thanks for the help!
Here's a suggestion. Create a DataSet with tables that describe your character sheet fields. Then create an instance of that DataSet and add a record with default (mostly blank) values to the table.
Now you can bind the columns to text boxes like this. (I'm doing this from memory, so forgive me if it doesn't compile - it should at least point you in the right direction
Dim ds As New CharacterDataSet ' Whatever you call your dataset
Dim bs As New BindingSource(ds, ds.CharacterTable.TableName)
bs.MoveFirst()
' Note, if you end up having more than one record, you can use bs.Filter
' to select which record the BindingSource points to.
txtCharacterName.DataBindings.Add("Text", bs, "CharacterName") ' Where CharacterName is the name of the column in the table
cboCharacterRace.DataBindings.Add("SelectedValue", bs, "Race") ' For a ComboBox
Also, if you want to be more robust with your column names in the DataBindings.Add, you can do something like ds.CharacterTable.CharacterNameColumn.ColumnName. That way, you can't accidentally misspell the column name in the binding.
Now you can use DataSet.WriteXML to write out the the whole dataset in one shot.

assignging text file contents to variable

Stack!
I'm currently trying to code a neat little function in Visual Basic that deletes my entire file system for my program depending on the contents of one text file.
If my text file contains the number 0 by itself, my file system will be deleted. If it contains a 1 by itself, it will not delete the file system and carry on with its pathway of execution.
the problem I'm having is reading the file, then assigning the text file's contents to a variable (string), which then is used in an if statement to decide whether it deletes (then immediately recreates) the file system, or keeps it. Ideally I'd be using this primarily for when the user installs. By default, it is set to 0 so that it clears any stored content, then after creating my directory, the number turns to 1 so that it does not reset my programs content directory.
Here's my code. The first line is giving me difficulties -
Could not find file 'C:\Users\110fa_000\documents\visual studio 2013\Projects\Novation_Launchpad_Emulator\Novation_Launchpad_Emulator\bin\Debug\0'.
fileReader = File.ReadAllText(My.Resources.FirstTimeUse)
If fileReader = "0" Then
FirstTimeUse = True
End If
If you can help me, that'd be absolutely brilliant. I don't think there's any more information I can give sadly, but everything regarding the function, purpose, and error is there.

vb.net writing files of specific size

I am creating an application whereby I need to write files (many, many of them). However, I don't want to write files that are too big because the program that consumes them will crash :)
Essentially, I would like to create files that are no larger than a specific size (possibly 5MB). My data is of CSV format and I will be writing line by line or into some stringbuilder to create the file I need.
Question: Is there a way to write data and create a set of files that are no larger than a set size?
I assume you are creating CSV rows 1 at a time.
If you are using a StreamWriter on the file (hopefully you are, no need to hold it all in memory):
Create the new record (a string of CSV items).
Look at the StreamWriter's BaseStream.Length property (Caveat - You need to use AutoFlush to make that property correct with the data that's been written previously).
Add your stream position, new record's length, and your line separator's length (usually 1 or 2, depending on Cr, Lf, or CrLf), and see if it exceeds your threshold.
If no, write the line feed, the record, and continue. If yes, close your StreamWriter and open a new one for a new file, write the record, and continue.

How to print certain lines of an input text file to another file in VB

I have a large file which i am writing to a smaller file in VB, i just dont know how to select lines from an input file that i opened.
I would like to keep the first 12 lines of the large file and them copy every 3rd line into the new output.
Any help?!
You can do this with a StreamReader - just open one on the file, then you can call ReadLine() on it as many times as you need.
Easiest implementation would probably be a 0-to-11 (or 1-to-12) For loop, then a While where you read 2 and ignore them, then read the 3rd and write it.
Writing the new file can be done with StreamWriter, which just has a WriteLine() method to write the text.
The StreamReader and StreamWriter are generally the easiest ways to read and write text files.

A way to save a specific My.Settings Variable in VB.NET

in My.Settings i've alot of variables including a 36000 records Datatable and Couple Large Array Lists, now when i call My.Settings.Save() it saves all the variables which takes alot of time and it saves variables that haven't been changed, is there a way make it Save only a Specific Datatable or ArrayList?
My.Setting.Save()
'but what i want for example is something like
My.Settings.SomeDatatable.Save()
These settings are stored in an XML file. Since XML files do not store data in a fixed-width record format, there is no way to update a single node in an XML file without rewriting the whole thing. If it is too slow, I would recommend either:
Store these settings in multiple XML files, so that you only have to save the applicable file, but not the rest
Store the settings in the database where each row can be saved individually without rewriting the whole file
Databases store their data in fixed-width "pages" so that only the modified pages need to be rewritten, rather than the whole file.
What about saving your dataTable not within your Settings. You could make use of DataTable.WriteXml(). this would keep your settings much smaller and you can access them separately!
' save table
DataTable.WriteXml("yourFile.xml")
' load table
Dim newTable As New DataTable
newTable.ReadXml(fileName)
But if there is no other possibility this solution from SLaks will work too
' save table
Dim writer As New StringWriter()
table.WriteXml(writer)
My.MySettings.Default.TableXml = writer.ToString()
' load table
Dim reader As New StringReader(My.MySettings.Default.TableXml)
table.ReadXml(reader)