views:

31

answers:

1

Hello,

We have to learn VB.NET for the semester, my experience lies mainly with C# - not that this should make a difference to this particular problem.

I've used just about the most simple way to save a file using the .NET framework, but Windows 7 won't let me save the file anywhere (or anywhere that I have found yet). Here is the code I am using to save a text file.

Dim dialog As FolderBrowserDialog = New FolderBrowserDialog()
Dim saveLocation As String = dialog.SelectedPath
... Build up output string ...
Try
    ' Try to write the file.
    My.Computer.FileSystem.WriteAllText(saveLocation, output, False)
Catch PermissionEx As UnauthorizedAccessException
    ' We do not have permissions to save in this folder.
    MessageBox.Show("Do not have permissions to save file to the folder specified. Please try saving somewhere different.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch Ex As Exception
    ' Catch any exceptions that occured when trying to write the file.
    MessageBox.Show("Writing the file was not successful.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

The problem is that this using this code throws an UnauthorizedAccessException no matter where I try to save the file. I've tried running the .exe file as administrator, and the IDE as administrator.

Is this just Windows 7 being overprotective? And if so, what can I do to solve this problem? The requirements state that I be able to save a file!

Thanks.

+2  A: 

This code:

Dim dialog As FolderBrowserDialog = New FolderBrowserDialog()
Dim saveLocation As String = dialog.SelectedPath

Is giving you the location of a folder. Then you're trying to save a file with the same name as the folder. Instead, I assume you want to save a file inside that folder:

Dim saveLocation As String = dialog.SelectedPath
saveLocation = Path.Combine(saveLocation, "SomeFile.txt")

That will create a file called "SomeFile.txt" inside the selected folder.

Alternatively, instead of using FolderBrowserDialog to choose a folder, use SaveFileDialog to select the actual file instead.

Dean Harding
How silly. Thanks!