I have following code:
Dim fs As FileStream
fs = New FileStream(path, FileMode.Create)
Dim sw As StreamWriter
sw = New StreamWriter(os)
sw.Write(something)
sw.Flush()
Is this a correct way to do this? Do i need to put in some checks to see if file exists?
It depends on what you are trying to do. If you want to overwrite the file, then no.
FileMode.Createwill always overwrite an existing file, or if it doesn’t exist, create it:If you don’t want to overwrite an existing file, then yes you should check it. Something like this:
You’ll also notice that I used
CreateNewinstead ofCreate. This is an additional safety check to ensure that an existing file is never overwritten. WithCreateNew, an exception is raised if the file already exists. You should still check if it exists however, since we don’t want the exception to happen in the first place.