Write mutiple lines to a text file using Visual Basic - vb.net

I'm trying to check to see if a file exists, if so it does nothing. If the file does not exist is creates the text file. Then I want to write text to that file. Where am I going wrong with this code? I'm just trying to write multiple lines to the text file and that part is not working. It is creating the text file... just not writing to it.
Dim file As System.IO.FileStream
Try
' Indicate whether the text file exists
If My.Computer.FileSystem.FileExists("c:\directory\textfile.txt") Then
Return
End If
' Try to create the text file with all the info in it
file = System.IO.File.Create("c:\directory\textfile.txt")
Dim addInfo As New System.IO.StreamWriter("c:\directory\textfile.txt")
addInfo.WriteLine("first line of text")
addInfo.WriteLine("") ' blank line of text
addInfo.WriteLine("3rd line of some text")
addInfo.WriteLine("4th line of some text")
addInfo.WriteLine("5th line of some text")
addInfo.close()
End Try

You don't seem to be properly releasing the resources you allocated with this file.
Make sure that you always wrap IDisposable resources in Using statements to ensure that all resources are properly released as soon as you have finished working with them:
' Indicate whether the text file exists
If System.IO.File.exists("c:\directory\textfile.txt") Then
Return
End If
Using Dim addInfo = File.CreateText("c:\directory\textfile.txt")
addInfo.WriteLine("first line of text")
addInfo.WriteLine("") ' blank line of text
addInfo.WriteLine("3rd line of some text")
addInfo.WriteLine("4th line of some text")
addInfo.WriteLine("5th line of some text")
End Using
but in your case using the File.WriteAllLines method seems more appropriate:
' Indicate whether the text file exists
If System.IO.File.exists("c:\directory\textfile.txt") Then
Return
End If
Dim data As String() = {"first line of text", "", "3rd line of some text", "4th line of some text", "5th line of some text"}
File.WriteAllLines("c:\directory\textfile.txt", data)

It all works great! - This is not the best way to create and write to a file - I'd rather create the text I want to write and then just write it to a new file, but given your code, all that is missing is having to close the created file before writing to it.
Just change this line:
file = System.IO.File.Create("c:\directory\textfile.txt")
to:
file = System.IO.File.Create("c:\directory\textfile.txt")
file.close
All the rest will work.

file = System.IO.File.Create("path")
Close the file once created then try to write to it.
file.Close()
Dim addInfo As New System.IO.StreamWriter("path")

Related

Remove double quotes in the content of text files

I am using a legacy application where all the source code is in vb.net. I am checking if the file exists and if the condition is true replace all the " in the contents of the file. For instance "text" to be replaced as text. I am using the below code.
vb.net
Dim FileFullPath As String
FileFullPath = "\\Fileshare\text\sample.txt"
If File.Exists(FileFullPath) Then
Dim stripquote As String = FileFullPath
stripquote = stripquote.Replace("""", "").Trim()
Else
'
End If
I get no errors and at the same time the " is not being replaced in the content of the file.
Data:
ID, Date, Phone, Comments
1,05/13/2021,"123-000-1234","text1"
2,05/13/2021,"123-000-2345","text2"
3,05/13/2021,"123-000-3456","text2"
Output:
1,05/13/2021,123-000-1234,text1
2,05/13/2021,123-000-2345,text2
3,05/13/2021,123-000-3456,text2
You can read each line of the file, remove the double-quotes, write that to a temporary file, then when all the lines are done delete the original and move/rename the temporary file as the filename:
Imports System.IO
'...
Sub RemoveDoubleQuotes(filename As String)
Dim tmpFilename = Path.GetTempFileName()
Using sr As New StreamReader(filename)
Using sw As New StreamWriter(tmpFilename)
While Not sr.EndOfStream
sw.WriteLine(sr.ReadLine().Replace("""", ""))
End While
End Using
End Using
File.Delete(filename)
File.Move(tmpFilename, filename)
End Sub
Add error handling as desired.
The best way to go about this depends on the potential size of the file. If the file is relatively small then there's no point processing it line by line and certainly not using a TextFieldParser. Just read the data in, process it and write it out:
File.WriteAllText(FileFullPath,
File.ReadAllText(FileFullPath).
Replace(ControlChars.Quote, String.Empty))
Only if the file is potentially large and reading it all in one go would require too much memory should you consider processing it line by line. In that case, I'd go this way:
'Let the system create a temp file.
Dim tempFilePath = Path.GetTempFileName()
'Open the temp file for writing text.
Using tempFile As New StreamWriter(tempFilePath)
'Open the source file and read it line by line.
For Each line In File.ReadLines(FileFullPath)
'Remove double-quotes from the current line and write the result to the temp file.
tempFile.WriteLine(line.Replace(ControlChars.Quote, String.Empty))
Next
End Using
'Overwrite the source file with the temp file.
File.Move(tempFilePath, FileFullPath, True)
Note the use of File.ReadLines rather than File.ReadAllLines. The former will only read one line at a time where the latter reads every line before you can process any of them.
EDIT:
Note that this:
File.Move(tempFilePath, FileFullPath, True)
only works in .NET Core 3.0 and later, including .NET 5.0. If you're targeting .NET Framework then you have three other options:
Delete the original file (File.Delete) and then move the temp file (File.Move).
Copy the temp file (File.Copy) and then delete the temp file (File.Delete).
Call My.Computer.FileSystem.MoveFile to move the temp file and overwrite the original file in one go.
TextFieldParser is probably the way to go.
Your code with a few changes.
Static doubleQ As String = New String(ControlChars.Quote, 2)
Dim FileFullPath As String
FileFullPath = "\\Fileshare\text\sample.txt"
If IO.File.Exists(FileFullPath) Then
Dim stripquote As String = IO.File.ReadAllText(FileFullPath)
stripquote = stripquote.Replace(doubleQ, "").Trim()
Else
'
End If
Note the static declaration. I adopted this approach because it confused the heck out of me.

VB Getting The SubFolder name and saving it to a Text file

I want to get The Subfolder Name Listed in my Textfile.
I don't want to see the path for the SubFolder.
I finally got a way to show only to my VS Console. But If i try to save it to my txt file it keeps on writing only the first line even though I used For. Please Help Me!
Here's the code that writes to the console
Dim di As New IO.DirectoryInfo(startPath)
Dim Drs() As IO.DirectoryInfo = di.GetDirectories()
For Each dr As IO.DirectoryInfo In Drs
Console.WriteLine(dr.Name)
Next
This is the code that I tried to Write It on a txt file. It only writes 1 Line
For Each Dir As String In Directory.GetDirectories(startPath)
My.Computer.FileSystem.WriteAllText("C:\Test.txt", Dir, False)
Next
The Expected Output is
SubFolder1
SubFolder2
SubFolder3
SubFolder4
SubFolder5
Like this in txt file
You are using the wrong method, WriteAllText always overwrites the complete file, you want to append a new line. You could use File.AppendAllText:
For Each Dir As String In Directory.GetDirectories(startPath)
System.IO.File.AppendAllText("C:\Test.txt", Dir)
Next
Another option, use a StreamWriter, it has a constructor that takes a Boolean to append text:
Using writer As New System.IO.StreamWriter(startPath, True)
For Each Dir As String In Directory.GetDirectories(startPath)
writer.WriteLine(Dir)
Next
End Using

How to fix IO.File.ReadAllText not reading file

I'm writing the file like this:
Dim objWriter As New System.IO.StreamWriter("C:\Users\Administrador\Documents\div.dat")
objWriter.Write(data)
objWriter.Close()
And reading it like this
Dim line As String = IO.File.ReadAllText("C:\Users\Administrador\Documents\div.dat")
However line is simply empty, no error is returned, the file does exist, and I can open it with notepad and it has plain text inside.

Write to a specific line in txt file when the line is empty

I am working on file writing in Vb.net. I know how to override a specific line in a text file but when it is empty or equal to "" , it fails.
I tried with
Dim lines() As String = System.IO.File.ReadAllLines("filepath")
lines(4) = "to replace text"
System.IO.File.WriteAllLines(filepath, lines)
It shows a Index out of array exception. It might be because the line in the file is empty.
Thank you

rich textbox combines all lines into one when saved as txt file?

I have a rich textbox in vb.net, which contains several lines of text however when I try and save the text to a .txt file all the lines are combined into one???
How can I overcome this?
what i did try was:
Dim MYLINES As Object
For Each MYLINES In RichTextBox1.Text
objWriter.WriteLine(MYLINES.ToString & Environment.NewLine)
Next
objWriter.Close()
however this simply placed every single character on a difrent line...
Save it as a .RTF file (instead of .TXT), wich can process the line breaks directly. Thats an option.
Or you can wirte the lines individually:
Dim sw As New System.IO.StreamWriter(sFileName)
For Each sLine as String in TextBox1.Lines
sw.WriteLine(sLine)
Next
sw.Close()
The method WriteLine already adds a line break at the end. It more or less the same as:
.Write(sLine & Enviroment.NewLine())