Write a string to a txt file

Cracken

Member
Joined
Sep 30, 2008
Messages
15
Location
England UK
Programming Experience
Beginner
Hi

I am building a string from a combo box but I cant get it to save to a text file.
Could anyone advise me on a simple way to write a string to this file and add to it ?

Here's my code I tried so far:
VB.NET:
    Private Sub cbZones_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbZones.SelectedIndexChanged
        txtString.Text += cbZones.Text + "/"
    End Sub

    Private Sub btnWrite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWrite.Click
        Dim fs As FileStream
        File.Create("C:\zoning.txt")
        Dim sw As StreamWriter = New StreamWriter(fs)
        sw.Write(txtString.Text)
        sw.Flush()
        sw.Close()
    End Sub

Thanks in advance.

Mark
 
Last edited by a moderator:
btnWrite.Click:

VB.NET:
Dim sw As StreamWriter("C:\zoning.txt", False)
sw.Write(txtString.Text)
sw.Close()

I would suggest using & rather than + for your concatenation.
 
Hi

Sorry for the late reply, that worked. I am now trying to populate the combo box from a txt file, I can populate a text box with the following code but it does not work on a combo box ?
VB.NET:
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        txtString.Text = """"
        Dim tCommands As String = "C:\zoning.txt"
        Dim TextLine As String

        If System.IO.File.Exists(tCommands) = True Then
            Dim objReader As New System.IO.StreamReader(tCommands)
            Do While objReader.Peek() <> -1
                TextLine = TextLine & objReader.ReadLine() & vbNewLine
            Loop
            [COLOR="YellowGreen"]'cmbCommand.Text = TextLine[/COLOR]
            TextBox1.Text = TextLine
        Else
            MsgBox("File Does Not Exist")
        End If
    End Sub
Not sure what I am missing ?

Mark
 
Look at the Lines property for the textbox you'll see it listed as a String[] Array.

Look at the Items property for the combobox and you'll see it listed as a (Collection).

VB.NET:
		Dim sr As New IO.StreamReader("C:\zoning.txt")

		For Each Line As String In sr.ReadToEnd.Split(Environment.NewLine)
			If Line.Trim() <> String.Empty Then
				Me.ComboBox1.Items.Add(Line)
			End If
		Next
 
If you already know there's no blank lines in the text file you can reduce the over head and do this:
VB.NET:
Dim sr As New IO.StreamReader("C:\zoning.txt")
Me.ComboBox1.Items.AddRange(sr.ReadToEnd.Split(Environment.NewLine))
sr.Close()
 
Back
Top