How do you store strings in a .txt file? - vb.net

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

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.

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 :)

Related

excel vba button to add text to a file

I am creating a spreadsheet with a button which creates a new file, then adds text to the file. I can't seem to get it working properly. (It is actually json, but for my purposes it is just raw text being inserted into a file.)
This is the code i have so far. It creates a new file and puts some text in it, I can't get the formatting of the text to come out how I want it. I don't really understand why the quotes appear in the output.
Private Sub GENERATE_ORDER_BUTTON_Click()
Dim path As String
path = "H:\order.json"
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.createtextfile(path, True)
a.WriteLine ("{")
a.Close
Dim outputstring As String
outputstring = "test" & "anothertest"
Open path For Append As #1
Write #1, outputstring
Close #1
End Sub
What i am finding is the output comes out like this:
{
"testanothertest"
The ultimate goal is to create a file with the indentations, quotes etc exactly as it is below.
{
"BASE_CE": [
{
"CE_HOSTNAME": "TESTCE-DCNCE-01",
"NEW": "NEW",
How to create and write to a txt file using VBA
I think this could maybe help you.
Cause if you use print,it doesn't appear to be formated like you dont want it to be...
Private Sub GENERATE_ORDER_BUTTON_Click()
Dim path As String
path = "J:\order.json"
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.createtextfile(path, True)
a.WriteLine ("{")
a.Close
Dim outputstring As String
outputstring = "test" & "anothertest"
Open path For Append As #1
Print #1, outputstring
Close #1
End Sub

Writing/Reading from text files in VB.net

I am a student in computer science and for a project I need to be able to read from a text file in a way that each line is assigned to a space within an array. This should happen so that each line of text file is read in the order that it appears in the text file. I would also appreciate any methods of writing to a text file as well.
If this question is already explained, could you please direct me to the existing answer.
Things to note:
1) I am coding in a console application in VB.NET
2) I am relatively new at coding
You can do it like this:
Dim sFile As String = "D:\File.txt"
Dim aLines As String() = System.IO.File.ReadAllLines(sFile)
System.IO.File.WriteAllLines(sFile, aLines)
Here's a sample from the official documentation:
Imports System.IO
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
Dim sw As StreamWriter
' 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"}
File.WriteAllLines(path, createText)
End If
' This text is always added, making the file longer over time
' if it is not deleted.
Dim appendText As String = "This is extra text" + Environment.NewLine
File.AppendAllText(path, appendText)
' Open the file to read from.
Dim readText() As String = File.ReadAllLines(path)
Dim s As String
For Each s In readText
Console.WriteLine(s)
Next
End Sub
End Class
Remarks
This method opens a file, reads each line of the file, then adds each line as an element of a string array. It then closes the file. A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating carriage return and/or line feed.
Module Module1
Sub Main()
'Declare four variables
Dim oReader As New System.IO.StreamReader(".\archive01.txt") 'This file has to exist in the aplication current directory.
Dim oWriter As New System.IO.StreamWriter(".\archive02.txt") 'This file will be created by the software.
Dim oArray() As String = {}
Dim oString As String = Nothing
'For reading from .\archive01.txt and to load in oArray().
oString = oReader.ReadLine
While Not oString Is Nothing
If UBound(oArray) = -1 Then 'Ubound = Upper Bound, also exist LBound = Lower Bound.
ReDim oArray(UBound(oArray) + 1)
Else
ReDim Preserve oArray(UBound(oArray) + 1)
End If
oArray(UBound(oArray)) = New String(oString)
oString = oReader.ReadLine
End While
oReader.Close()
'For writing from oArray() to .\archive02.txt.
For i = 0 To oArray.Count - 1 Step 1
oWriter.WriteLine(oArray(i))
Next
oWriter.Close()
End Sub
End Module
Hi, try with this code. It works well. I hope that this helps to you to learn how to do this kind of things. Thank you very much. And happy codding!. :)

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()

Illegal Characters in path when grabbing text from a file?

I'm getting illegal characters in path, but the directory (the path) will be different for everyone, so I'm not setting a value for the "path", it's what the user chooses in the file explorer.
I haven't seen a solution for VB.net yet so here's the code I have now:
myFileDlog.InitialDirectory = "c:\"
myFileDlog.Filter = "Txt Files (*.txt)|*.txt"
myFileDlog.FilterIndex = 2
myFileDlog.RestoreDirectory = True
If myFileDlog.ShowDialog() =
DialogResult.OK Then
If Dir(myFileDlog.FileName) <> "" Then
Else
MsgBox("File Not Found",
MsgBoxStyle.Critical)
End If
End If
'Adds the file directory to the text box
TextBox1.Text = myFileDlog.FileName
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(myFileDlog.FileName)
Dim lines() As String = IO.File.ReadAllLines(fileReader)
At Dim lines() As String = IO.File.ReadAllLines(fileReader)
It breaks with the Illegal Characters in Path exception, and I'm not sure how to test where the illegal character is, because it's grabbing from your own file directory. Any help with this?
The problem originated from this line:
Dim fileReader As String = My.Computer.FileSystem.ReadAllText(myFileDlog.FileName)
fileReader takes all string contents from the corresponding file name and pass it into File.ReadAllLines method at next line, throwing ArgumentException with illegal file path message if illegal characters found inline.
Correct way to read file contents using ReadAllLines is using predefined file path or directly using FileDialog.FileName property as argument given below:
Using myFileDlog As OpenFileDialog = New OpenFileDialog()
' set dialog filters here
If (myFileDlog.ShowDialog() = DialogResult.OK) Then
If Dir(myFileDlog.FileName) <> "" Then
Dim lines() As String = File.ReadAllLines(myFileDlog.FileName)
For Each line As String In lines
' do something with file contents
Next
Else
' show "file not found" message box
End If
End If
End Using
Since ReadAllLines already being used to fetch all file contents, usage of ReadAllText may be unnecessary there.

How to create .key file with specific text

I've been trying to make a program that is able to create a file with a .key extension, which contains a 5 line text.
It is fundamental to have 5 lines, otherwise it won't work.
I use
Dim filepath As String = TextBox1.Text + "\\rarreg.key"
Dim rarreg As New IO.StreamWriter(filepath, True)
rarreg.Write(String.Join(Environment.NewLine, hiddenTxt))
The hiddenTxt contains all the text needed and it's multilined.
However, when I click on the button to call this functions, it succesfully creates the file, but it comes empty.
Try this
' Add any initialization after the InitializeComponent() call.
Dim filepath As String = ""
Dim dialog As New SaveFileDialog
dialog.DefaultExt = "key"
dialog.FileName = "rarreg.key"
dialog.InitialDirectory = "c:\temp"
Dim results As DialogResult = dialog.ShowDialog()
If results <> Windows.Forms.DialogResult.Cancel Then
filepath = dialog.FileName
End If​