¿Debería verificar si existe una ruta de archivo antes de transmitir texto en el archivo?

Tengo el siguiente código:

Dim fs As FileStream
fs = New FileStream(path, FileMode.Create)

Dim sw As StreamWriter
sw = New StreamWriter(os)

Is this a correct way to do this? Do i need to put in some checks to see if file exists?

preguntado el 03 de mayo de 12 a las 16:05

1 Respuestas

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.Create will always overwrite an existing file, or if it doesn't exist, create it:


Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This operation requires FileIOPermissionAccess.Write permission. System.IO.FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.

If you don't want to overwrite an existing file, then yes you should check it. Something like this:

If Not File.Exists(path) Then
    Using fs As New FileStream(path, FileMode.CreateNew), sw As New StreamWriter(fs)
    End Using
End If

You'll also notice that I used CreateNew en lugar de Create. This is an additional safety check to ensure that an existing file is never overwritten. With CreateNew, 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.

contestado el 03 de mayo de 12 a las 16:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.