MerajA
MerajA

Reputation: 194

How do you store strings in a .txt file?

I've been creating a program over the past few days. The program stores a string "Dim info As String = Nothing" where the input is asked later.

EG: I input "Hello World!" to the variable 'info', how do I store the value of 'info' (Hello World!) to a .txt file? Or is this not possible?

(Still a beginner to vb.net, looking for simple answers.)

Attempt 1 (Find error please):

Sub Main()
    Dim path As String = "C:\VBTextFiles\Test1.txt"
    Dim stringex As String = "Hello world!"
    File.WriteAllText(path, stringex)
End Sub

Upvotes: 0

Views: 6108

Answers (2)

Genesis Del Carmen
Genesis Del Carmen

Reputation: 1

Dim path As String = "c:\temp\MyTest.txt" 
' This text is added only once to the file. 
If File.Exists(path) = True Then 
  ' Create a file to write to. 
  Dim createText As String = "Hello and Welcome" + Environment.NewLine
  File.WriteAllText(path, createText)
End If 

Change False for True in the line 3 :)

Upvotes: -1

Victor Zakharov
Victor Zakharov

Reputation: 26454

You could use IO.File.WriteAllText to create a file and write your info into it.

This page has examples for Create and Append. Here is a revelant part for Create:

Dim path As String = "c:\temp\MyTest.txt" 
' This text is added only once to the file. 
If File.Exists(path) = False Then 
  ' Create a file to write to. 
  Dim createText As String = "Hello and Welcome" + Environment.NewLine
  File.WriteAllText(path, createText)
End If 

For APPEND, use AppendAllText. See Example.

Upvotes: 3

Related Questions