I'm programming an application that must save a .txt file in user PC. I am currently using this code:
Dim filepath As String = "G:\Username.txt"
If Not System.IO.File.Exists(filepath) Then
And used this code for other local drives as
D:\. Like this example
Dim filepath2 As String = "D:\Username.txt"
If Not System.IO.File.Exists(filepath2) Then
Dim filepath4 As String = "F:\Username.txt"
If Not System.IO.File.Exists(filepath4) Then
This code is working, however I am facing a problem If user PC just has 2 local drives except drive
C:\ such as
D:\. When the code that attempts to save the .txt file to drive
F:\ the code fails to execute with a
System.IO.DirectoryNotFoundException. I am looking to somehow skip the code if the drive is not available and to only execute the code when that local drive (e.g.
F:\) is available.
Best How To :
As said in the comments to your question, your code may be creating a file on the specified drives, however it is leaving a handle open on the files. When the Garbage Collection is comes along, the open handles on the files are removed. however if you were to try and modify those files while the application has them open you'll find that the file is locked. The method you are using,
IO.File.Create returns a
FileStream object. This object supports IDisposable and as such you should either be cleaning up after yourself, or implementing the
Secondly, as the other answer has pointed out, your logic for checking if the file exists is flawed in that you'll get a false positive if the drive itself doesn't exist, not just the file. On a different thought path, using
File.Exists() is almost never useful as it will never give you accurate results in real-time during run-time. There is always a possibility that the file's existence may change from the time that
File.Exists() is called to when your application attempts to access the file; commonly known as a race condition. Instead you should be attempting to do whatever it is you are doing and then handling any type of exceptions that are occurring.
Option Strict On
Option Explicit On
Dim fleName As String = "Username.txt"
For Each drvInfo As DriveInfo In DriveInfo.GetDrives
If drvInfo.DriveType = DriveType.Fixed AndAlso drvInfo.Name <> "C:\" Then
Dim fleStream As FileStream = File.Open(drvInfo.Name & fleName, FileMode.Create, FileAccess.Write)
' Do some stuff here
' Or implement the 'Using' directive
Using fleStream As FileStream = File.Open(drvInfo.Name & fleName, FileMode.Create, FileAccess.Write)
'do some stuff here
Catch ex As Exception