write text file

futhon

Member
Joined
Feb 9, 2010
Messages
9
Programming Experience
Beginner
Hi,

I am trying to create a textfile and write some lines into the textfile. However, the code that i am using can only write when the textfile is already created in the directory.

For this case, can i actually allow my script to search if a textfile is being created, if not create a textfile ???

VB.NET:
Dim pathdir As String = "C:\workingdir\test.txt"

            If System.IO.File.Exists(pathdir) = True Then
                Dim objWriter As New StreamWriter(pathdir)
                objWriter.Write("This is a test file!!!")
                objWriter.Close()
                MsgBox("Text written to file")
            Else
                MsgBox("File Does Not Exist")
            End If

Thanks
 
You don't have to care whether there's a file already or not. Just create the StreamReader as you are and a new file will be created automatically, overwriting the existing file if there is one.
 
I cant seem to do so.

Where should i place the StreamReader??
Do i need the StreamReader as i will not read the content in the file..

When i use
Dim objWriter As New StreamWriter(pathdir)
a message box will appear to inform "File Does Not Exist".
 
I did an error log on my last app and it was really straight forward using the File class.
Just import the system.io
VB.NET:
Imports System.IO
and then use:
VB.NET:
        File.AppendAllText(path, txt)  ' <<< This one if you want to append the text at the end of the file
        File.WriteAllText(path, txt)   ' <<< This one if you want to overwrite if a file already exist

in both cases it will create a file if it doesn't already exist.
 
jmc meant StreamWriter of course. And as said all StreamWriter constructors automatically create file it doesn't exist. You can also use the Boolean parameter in constructor to choose if to append or not. The single call as suggest by Budius is naturally better if you only have a single string value to output at current time of execution.
 
Back
Top