如何避免拒绝访问(只检查文件名)

时间:2014-12-02 18:02:33

标签: vb.net visual-studio-2010

所以我在这里有一个非常基本的问题......我们有一个依赖于存储设置的xml文件的应用程序。偶尔此文件已损坏,应用程序将在启动时失败。我想编写一个可以找到USED文件和BACKUP文件的应用程序。应用程序使用的文件并不总是出于各种原因(10年的更改等)存储在同一位置,但它的名称始终相同。

这个想法是我写这个简单的应用程序,它可以找到系统上的所有文件的情况(通常是一个或两个硬盘驱动器),很明显使用哪个,哪个是备份。

简单......但在迭代使用此代码时

Private Sub Command1_Click(sender As System.Object, e As System.EventArgs) Handles Command1.Click
    'variable to hold each hdd name eg: c:\
    Dim hdd As String




    Try

        For Each drive As IO.DriveInfo In IO.DriveInfo.GetDrives
            'asign the variable hdd a name for this run through
            hdd = drive.Name

            'search the hdd for the file user.config

            For Each filename As String In IO.Directory.GetFiles(hdd, "user.config", IO.SearchOption.AllDirectories)

                'variable to hold the path for each found file
                Dim file As String = IO.Path.GetFullPath(filename)


                'add each found file to the list
                List1.Items.Add(file)

            Next


        Next

    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
    'iterate through each found drive





End Sub

我得到的问题是拒绝访问... enter image description here

所以我认为我应该能够在我做任何事情之前检查权限吗?但后来我想我实际上并没有尝试做任何事情,只是读得对吗?或者我错过了什么......

我尝试过更改权限,以管理员身份运行VS2010等等。这些都不起作用。

TIA

2 个答案:

答案 0 :(得分:2)

RtBackup是一个系统文件夹,如果查看权限,只有系统(甚至管理员)才能访问它。我想你可以将你的程序作为系统运行,但这听起来像是一个愚蠢的想法。我会抓住异常,也许将其记录在某处或显示控制台消息并继续前进。

答案 1 :(得分:0)

你说:"我尝试过更改权限,以管理员身份运行VS2010等等。这些都没有用。"

当你说,"尝试更改权限"时,你的意思是什么?您尝试更改权限的内容是什么?正如你所发现的那样,以管理员身份运行VS并不会有任何好处。

问题是文件夹RtBackup的权限。一个选项(可能不是最好的?)是去

C:\Windows\System32\LogFiles\WMI

右键单击RtBackup文件夹并选择“属性”,转到“安全”选项卡,“编辑”,“添加”,然后键入" Everyone"在底部框中,单击“确定”。在“Rtbackup的权限”窗口中,确保突出显示“所有人”,然后将其设置为“完全控制”。好。确定。

请记住,在执行此操作时,您已将此文件夹打开,以便完全访问所有人和所有内容。这可能足以进行测试。当您想要发布时,您想要做的是找出(或指定)您的应用运行的用户,并授予该用户读取权限。

修改

如果您想使用try-catch跳过您没有权限的案例,请按以下格式设置代码格式:

    For Each drive As IO.DriveInfo In IO.DriveInfo.GetDrives

        'asign the variable hdd a name for this run through
        hdd = drive.Name

        Try

            'search the hdd for the file user.config
            For Each filename As String In IO.Directory.GetFiles(hdd, "user.config", IO.SearchOption.AllDirectories)

            'variable to hold the path for each found file
                Dim file As String = IO.Path.GetFullPath(filename)

                'add each found file to the list
                List1.Items.Add(file)

            Next

        Catch ex As Exception
           ' handle error here, or just do nothing
        End Try

    Next