You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

此前正常的目录扫描程序突发Access Denied错误求助

问题描述

我有一个用于扫描目录并列出其中文件夹的程序,此前运行正常,但现在突然出现**Access Denied(访问被拒绝)**错误。

已检查文件权限无异常,更换了程序运行用户的密码以确保未过期,甚至创建了测试目录,但程序仍无法访问。尝试以管理员身份运行程序依旧失败。

报错的代码行是:

Using file2 As New IO.FileStream(foldername, IO.FileMode.Open)

已尝试以下操作:

  • 创建拥有完全权限的测试文件夹
  • 修改程序运行用户的密码
  • 创建新项目并重新编写代码
  • 使用管理员账户登录执行程序
  • 更新Visual Studio至最新版本

附程序代码如下:

Imports System.ComponentModel
Imports System.Text
Imports System.IO
Imports System.IO.Compression

Partial Public Class Form1
    Public SQL As New SQLControl
    Public Sub New()
        InitializeComponent()
    End Sub

    Private Sub btn_analysis_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btn_analysis.ItemClick
        Dim fileEx As String
        Dim sqltxt As String
        Dim ProtectedFileFlip As String
        ProtectedFileFlip = "jigsawdummyvalue"
        Dim FolderFlip As String
        FolderFlip = "jigsawdummyvalue"
        Dim FilePathCount As Integer
        FilePathCount = 1
        Dim FilesCount As Integer
        FilesCount = 1
        Dim DFilesCount As Integer
        DFilesCount = 1
        Dim TrueRec As Boolean
        Dim FileExt As String
        Dim ProtectedFolderCount As Integer
        Dim ProtectedFileCount As Integer
        Dim FileDeletion As Integer
        Dim yy As Integer
        Dim xx As Integer
        Dim aa As Integer

        TrueRec = False
        FilePathCount = 1
        FilesCount = 1

        'Load Protected File Paths
        sqltxt = "SELECT * FROM FilePath WHERE Action = 'Retain'"
        sqltxt = sqltxt.Replace("""", "'")
        SQL.ExecQuery(sqltxt)
        Dim ProtectedPath(SQL.RecordCount)
        For Each r As DataRow In SQL.DBDT.Rows
            ProtectedPath(FilePathCount) = r.ItemArray(1)
            FilePathCount = FilePathCount + 1
        Next
        'Load File Paths to delete
        sqltxt = "SELECT * FROM FilePath WHERE Action = 'Delete'"
        sqltxt = sqltxt.Replace("""", "'")
        SQL.ExecQuery(sqltxt)
        Dim RemoveFiles(SQL.RecordCount)
        For Each r As DataRow In SQL.DBDT.Rows
            RemoveFiles(DFilesCount) = r.ItemArray(1)
            DFilesCount = DFilesCount + 1
        Next
        'Load Protected File Extensions
        sqltxt = "SELECT * FROM Definitions"
        sqltxt = sqltxt.Replace("""", "'")
        SQL.ExecQuery(sqltxt)
        Dim ProtectedFile(SQL.RecordCount)
        For Each r As DataRow In SQL.DBDT.Rows
            ProtectedFile(FilesCount) = r.ItemArray(6)
            FilesCount = FilesCount + 1
        Next
        'Create file output header
        ListBox1.Items.Add("JIGSAW FILE ANALYSIS UTILITY VERSION 1.0.0")
        ListBox1.Items.Add("Analysis commenced at " & Now())
        ListBox1.Items.Add("Loaded " & FilePathCount - 1 & " protected file path definitions.")
        ListBox1.Items.Add("Loaded " & FilesCount - 1 & " protected file extention definitions.")
        ListBox1.Items.Add("Loaded " & DFilesCount - 1 & " file path deletion definitions.")
        ListBox1.Items.Add("----------------------------------------------------------------")
        Refresh()

        'Try
        Const foldername = "C:\justtest"
        Using file2 As New IO.FileStream(foldername, IO.FileMode.Open)
                fileEx = file2.Name
                aa = aa + 1
                For x = 1 To DFilesCount - 1
                    If fileEx.Contains(RemoveFiles(x)) = True And Not fileEx.Contains(FolderFlip) Then
                        ListBox1.Items.Add(fileEx & " Located in " & RemoveFiles(x) & " contents of folder will be removed.")
                        FolderFlip = RemoveFiles(x)
                        GoTo mole
                    End If
                    If fileEx.Contains(RemoveFiles(x)) = True And fileEx.Contains(FolderFlip) = True Then
                        GoTo mole
                    End If
                Next
                For x = 1 To FilePathCount - 1
                    If fileEx.Contains(ProtectedPath(x)) = True And Not fileEx.Contains(ProtectedFileFlip) Then
                        ListBox1.Items.Add(fileEx & " Located in " & ProtectedPath(x) & " ignored, protected folder, all files will be archived.")
                        ProtectedFolderCount = ProtectedFolderCount + 1
                        ProtectedFileFlip = ProtectedPath(x)
                        TrueRec = True
                        GoTo mole
                    End If
                    If fileEx.Contains(ProtectedPath(x)) = True And fileEx.Contains(ProtectedFileFlip) = True Then
                        GoTo mole
                    End If
duck:
                Next x
                For x = 1 To FilesCount
                    yy = 0
                    xx = 1
                    For y = 1 To Len(fileEx)
                        FileExt = Mid(fileEx, Len(fileEx) - yy, xx)
                        If FileExt.Contains(".") Then
                            FileExt = Mid(fileEx, Len(fileEx) - (yy - 1), xx - 1)
                            GoTo rabbit
                        End If
                        yy = yy + 1
                        xx = xx + 1
                    Next y
rabbit:
                    For gg = 1 To FilesCount - 1
                        If FileExt = ProtectedFile(gg) Then
                            ListBox1.Items.Add(fileEx & "  ignored, protected file. File will be archived.")
                            ProtectedFileCount = ProtectedFileCount + 1
                            TrueRec = True
                            GoTo frog
                        End If
                    Next gg
                Next x
                Refresh()
            End Using
            'Catch
            '    ListBox1.Items.Add("Unable to report on file.")
            '    aa = aa + 1
            'End Try
frog:
        If TrueRec = False Then
            ListBox1.Items.Add(fileEx & " file will be deleted prior to archiving process.")
            FileDeletion = FileDeletion + 1
        End If
        TrueRec = False
        Refresh()
mole:
        Refresh()

        ListBox1.Items.Add("----------------------------------------------------------------")
        ListBox1.Items.Add("SUMMARY INFORMATION---------------------------------------------")
        ListBox1.Items.Add("Analysis completed at " & Now())
        ListBox1.Items.Add("Number of protected folders identified--- " & ProtectedFolderCount)
        ListBox1.Items.Add("Number of protected files identified------ " & ProtectedFileCount)
        ListBox1.Items.Add("Number of files which will be deleted----- " & FileDeletion)
        ListBox1.Items.Add("Number of files scanned ------------------ " & aa)
        MsgBox("Scan completed", vbOKOnly, "Completed")
    End Sub

End Class
问题解决

核心错误原因

用IO.FileStream打开文件夹路径(C:\justtest)是完全错误的用法。FileStream仅用于操作文件,不能用来打开目录,系统会直接拒绝这种非法操作,抛出Access Denied错误——这和权限无关,是API使用错误。

修正方案

要扫描目录里的文件,应该用Directory.GetFiles或Directory.EnumerateFiles获取所有文件路径,再逐个处理文件。同时去掉被注释的Try-Catch,它会掩盖真实错误。

修正后的核心代码片段

Const foldername = "C:\justtest"
' 遍历目录下所有文件(包括子目录)
For Each filePath As String In Directory.EnumerateFiles(foldername, "*", SearchOption.AllDirectories)
    aa += 1
    fileEx = Path.GetFileName(filePath) ' 获取文件名
    Dim fullPath = filePath ' 保留完整路径用于判断

    ' 检查删除路径规则
    Dim skipDeleteCheck As Boolean = False
    For x = 1 To DFilesCount - 1
        If fullPath.Contains(RemoveFiles(x)) Then
            If Not skipDeleteCheck Then
                ListBox1.Items.Add($"{fullPath} 位于 {RemoveFiles(x)},文件夹内容将被移除。")
                skipDeleteCheck = True
            End If
            GoTo mole ' 跳过后续检查,直接处理下一个文件
        End If
    Next

    ' 检查保护文件夹规则
    Dim isProtectedFolder As Boolean = False
    For x = 1 To FilePathCount - 1
        If fullPath.Contains(ProtectedPath(x)) Then
            If Not isProtectedFolder Then
                ListBox1.Items.Add($"{fullPath} 位于受保护文件夹 {ProtectedPath(x)},将被归档,忽略删除。")
                ProtectedFolderCount += 1
                isProtectedFolder = True
                TrueRec = True
            End If
            GoTo mole
        End If
    Next

    ' 提取文件扩展名(简化写法)
    FileExt = Path.GetExtension(filePath).TrimStart("."c)

    ' 检查保护文件扩展名规则
    For gg = 1 To FilesCount - 1
        If FileExt.Equals(ProtectedFile(gg), StringComparison.OrdinalIgnoreCase) Then
            ListBox1.Items.Add($"{fullPath} 是受保护文件,将被归档。")
            ProtectedFileCount += 1
            TrueRec = True
            GoTo mole
        End If
    Next

frog:
    If Not TrueRec Then
        ListBox1.Items.Add($"{fullPath} 将在归档前被删除。")
        FileDeletion += 1
    End If
    TrueRec = False
    Refresh()
mole:
    Continue For ' 继续下一个文件
Next

额外优化建议

  1. 替换GoTo语句:大量使用GoTo会让代码逻辑混乱,建议用Boolean标志位或提前退出循环替代。
  2. 变量初始化:ProtectedFolderCount、ProtectedFileCount等变量显式初始化会让代码更清晰。
  3. 路径判断优化:用Path.GetFullPath统一路径格式,避免因路径大小写、分隔符不一致导致的判断错误。
  4. 异常处理:给单个文件操作添加Try-Catch,捕获文件占用等特定异常,不要掩盖整个流程的错误。

内容的提问来源于stack exchange,提问作者Clamont

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 08:45:46