Reputation:
I can't create a folder in drive C: using VB.NET. It says "Access is Denied". I tried quite a lot of methods but it doesn't work. I have tried to use this code:
If my.Computer.FileSystem.DirectoryExists("C:\log.txt") Then
Using writer As System.IO.TextWriter = System.IO.File.CreateText("C:\log.txt")
writer.WriteLine(Me.Top & vbCrLf & "'top")
writer.WriteLine(Me.Left & vbCrLf & "'lrft") ''sa scriu
writer.WriteLine(Me.Width & vbCrLf & "'width")
writer.WriteLine(Me.Height & vbCrLf & "'height")
End Using
Else
Directory.CreateDirectory("C:\log.txt")
Using writer As System.IO.TextWriter = System.IO.File.CreateText("C:\log.txt")
writer.WriteLine(100 & vbCrLf)
writer.WriteLine(100 & vbCrLf) ''sa scriu
writer.WriteLine(100 & vbCrLf)
writer.WriteLine(100 & vbCrLf)
End Using
End If
What should I do?
Upvotes: 1
Views: 819
Reputation: 43743
The problem appears to be that you are mixing the concept of directories (i.e. folders) with that of files. First, you check to see if a folder called log.txt exists. If it does exist, then you try to create a new file by the same name in the same location. Conversely, if the log.txt folder doesn't exist, you create the folder, and then you try to create a file by the same name in the same location. Either way, it's always going to fail. You can't create a file called log.txt if there's already a folder by that same name in the same location.
I suspect that what you intended to do was to check if the folder C:\ existed before trying to create the file in that folder. For instance, something like this:
If My.Computer.FileSystem.DirectoryExists("C:\") Then
Using writer As System.IO.TextWriter = System.IO.File.CreateText("C:\log.txt")
' ...
End Using
Else
Directory.CreateDirectory("C:\")
Using writer As System.IO.TextWriter = System.IO.File.CreateText("C:\log.txt")
' ...
End Using
End If
That certainly would make more logical sense, but, in this particular case, it's a bit silly since C:\ is the root folder for the drive, so it will always exist (unless the drive volume doesn't exist, in which case creating the folder will fail anyway).
As Plutonix pointed out in the comments above, even if that does work for you, it's still bad practice. It's quite possible, if not likely, that the user will not have access to the root of the C: drive. It would be far preferrable to write to Isolated Storage, or the system's temporary folder, or the user's application data folder, or anywhere else that is more likely to be accessible.
Upvotes: 3