¿Debería verificar si existe una ruta de archivo antes de transmitir texto en el archivo?
Frecuentes
Visto 1,724 veces
1 Respuestas
1
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)
sw.Write("Something")
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 vb.net file-io or haz tu propia pregunta.