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

(VB.NET) 如何实现Windows文件夹及其内容的锁定功能?

使用VB.NET实现文件夹文件的编辑保护方案

完全可行,以下是两种符合你需求的实现方案:

方案一:修改文件只读属性

通过批量设置文件的只读属性,实现未解锁时无法编辑保存的效果,文件夹和文件保持可见。

锁定逻辑

遍历目标文件夹下的所有文件(包括子文件夹内的文件),将每个文件的只读属性设为True:

Sub LockFolderByReadOnly(folderPath As String)
    Dim dirInfo As New DirectoryInfo(folderPath)
    ' 遍历所有文件
    For Each fileInfo As FileInfo In dirInfo.GetFiles("*", SearchOption.AllDirectories)
        fileInfo.IsReadOnly = True
    Next
    ' 可选:标记文件夹为只读(Windows中文件夹只读是状态标记,不直接限制文件)
    dirInfo.Attributes = dirInfo.Attributes Or FileAttributes.ReadOnly
End Sub

解锁逻辑

遍历文件并取消只读属性:

Sub UnlockFolderByReadOnly(folderPath As String)
    Dim dirInfo As New DirectoryInfo(folderPath)
    For Each fileInfo As FileInfo In dirInfo.GetFiles("*", SearchOption.AllDirectories)
        fileInfo.IsReadOnly = False
    Next
    dirInfo.Attributes = dirInfo.Attributes And Not FileAttributes.ReadOnly
End Sub

优缺点

  • 优点:实现简单,程序无需后台运行,资源消耗极低
  • 缺点:用户可手动右键修改文件属性绕过,适合低强度防护场景

方案二:独占模式打开文件

通过以独占访问权限打开文件,让Windows误以为文件正在被使用,此时其他程序无法编辑保存该文件,文件保持可见。

锁定逻辑

对目标文件创建独占模式的FileStream并保持打开状态,需将流对象存储起来以便解锁时关闭:

' 全局存储打开的文件流,避免被GC回收
Private lockedStreams As New List(Of FileStream)

Sub LockFolderByExclusiveOpen(folderPath As String)
    Dim dirInfo As New DirectoryInfo(folderPath)
    For Each fileInfo As FileInfo In dirInfo.GetFiles("*", SearchOption.AllDirectories)
        Try
            ' 以独占模式打开文件,无共享权限
            Dim stream As New FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.None)
            lockedStreams.Add(stream)
        Catch ex As Exception
            ' 处理文件已被其他程序打开的情况
            Console.WriteLine($"无法锁定文件:{fileInfo.FullName},错误:{ex.Message}")
        End Try
    Next
End Sub

解锁逻辑

遍历存储的流对象并关闭,释放文件占用:

Sub UnlockFolderByExclusiveOpen()
    For Each stream As FileStream In lockedStreams
        If stream IsNot Nothing AndAlso stream.CanRead Then
            stream.Close()
        End If
    Next
    lockedStreams.Clear()
End Sub

注意事项

  • 程序必须保持运行状态,一旦关闭,所有流会被自动释放,文件解锁
  • 不建议对大量文件使用该方案,会占用较多系统句柄资源
  • 对于正在被其他程序使用的文件,无法通过该方式锁定

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 16:20:41