【问题标题】:VB.NET 2008, Windows 7 and saving filesVB.NET 2008、Windows 7 和保存文件
【发布时间】:2011-02-20 17:12:40
【问题描述】:

这学期我们必须学习 VB.NET,我的经验主要在于 C# - 并不是说​​这会对这个特定问题产生影响。

我已经使用了使用 .NET 框架保存文件的最简单的方法,但 Windows 7 不允许我将文件保存在任何地方(或我已经找到的任何地方)。这是我用来保存文本文件的代码。

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

问题在于,无论我尝试将文件保存在何处,使用此代码都会引发 UnauthorizedAccessException。我试过以管理员身份运行 .exe 文件,以管理员身份运行 IDE。

这仅仅是 Windows 7 保护过度吗?如果是这样,我该怎么做才能解决这个问题?要求说明我可以保存文件!

谢谢。

【问题讨论】:

    标签: vb.net windows-7 file-io file-permissions


    【解决方案1】:

    这段代码:

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

    给你一个文件夹的位置。然后您尝试使用 与文件夹名称相同的文件 保存文件。相反,我假设您想在该文件夹 inside 保存一个文件:

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

    这将在所选文件夹中创建一个名为“SomeFile.txt”的文件。

    或者,不要使用 FolderBrowserDialog 来选择文件夹,而是使用 SaveFileDialog 来选择实际文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多