vb.net - How to skip unavailable drive letters -
i'm programming application must save .txt file in user pc. using code:
dim filepath string = "g:\username.txt" if not system.io.file.exists(filepath) system.io.file.create(filepath) end if
and used code other local drives f:\
, e:\
, d:\
. example
dim filepath2 string = "d:\username.txt" if not system.io.file.exists(filepath2) system.io.file.create(filepath2) end if dim filepath4 string = "f:\username.txt" if not system.io.file.exists(filepath4) system.io.file.create(filepath4) end if
this code working, facing problem if user pc has 2 local drives except drive c:\
such g:\
, d:\
. when code attempts save .txt file drive f:\
code fails execute system.io.directorynotfoundexception
. looking somehow skip code if drive not available , execute code when local drive (e.g. f:\
) available.
as said in comments question, code may creating file on specified drives, leaving handle open on files. when garbage collection comes along, open handles on files removed. if try , modify files while application has them open you'll find file locked. method using, io.file.create
returns filestream
object. object supports idisposable , such should either cleaning after yourself, or implementing using
directive.
secondly, other answer has pointed out, logic checking if file exists flawed in you'll false positive if drive doesn't exist, not file. on different thought path, using file.exists()
never useful never give accurate results in real-time during run-time. there possibility file's existence may change time file.exists()
called when application attempts access file; commonly known race condition. instead should attempting whatever doing , handling type of exceptions occurring.
option strict on option explicit on imports system.io module module1 sub main() dim flename string = "username.txt" each drvinfo driveinfo in driveinfo.getdrives if drvinfo.drivetype = drivetype.fixed andalso drvinfo.name <> "c:\" try dim flestream filestream = file.open(drvinfo.name & flename, filemode.create, fileaccess.write) ' stuff here flestream.close() flestream.dispose() ' or implement 'using' directive using flestream filestream = file.open(drvinfo.name & flename, filemode.create, fileaccess.write) 'do stuff here end using catch ex exception console.writeline(ex.message) end try end if next end sub end module
Comments
Post a Comment