gpt4 book ai didi

f# 检查目录是否可访问 不工作

转载 作者:行者123 更新时间:2023-12-05 01:11:53 27 4
gpt4 key购买 nike

try (box (Directory.GetDirectories(dir) ))
with | :? System.UnauthorizedAccessException -> ()

我正在尝试检查该目录是否可访问,这样我就不会收到“访问被拒绝”错误,但它不起作用,它没有跳过 for 中的循环

最佳答案

通常不鼓励将异常用作控制流的一部分。最好在尝试枚举其内容之前检查对目录的适当访问权限。尝试这样的事情:

open System
open System.IO
open System.Linq
open System.Security.AccessControl
open System.Security.Principal

let checkSecurity =
let account = sprintf @"%s\%s" Environment.UserDomainName Environment.UserName
let identity = WindowsIdentity.GetCurrent()
let principal = identity |> WindowsPrincipal
let isAdmin = identity.Owner = identity.User
fun (dir: DirectoryInfo) ->
try
let acl = dir.GetAccessControl(AccessControlSections.All)
let rules = acl.GetAccessRules(true, true, typeof<NTAccount>)
rules.OfType<FileSystemAccessRule>()
|> Seq.filter (fun rule -> rule.IdentityReference.Value.Equals(account, StringComparison.CurrentCultureIgnoreCase) ||
(if rule.IdentityReference.Value.Equals("BUILTIN\Administrators", StringComparison.CurrentCultureIgnoreCase)
then isAdmin && principal.IsInRole(rule.IdentityReference.Value)
else principal.IsInRole(rule.IdentityReference.Value)))
|> Seq.exists (fun rule -> (rule.FileSystemRights &&& FileSystemRights.Read = FileSystemRights.Read) && rule.AccessControlType <> AccessControlType.Deny)
with | _ ->
false

let rec getFiles (dir: DirectoryInfo) =
[ if checkSecurity dir
then for file in dir.GetFiles("*") do yield file
for subDir in dir.GetDirectories("*") do yield! getFiles subDir
]

let dir = DirectoryInfo(@"C:\Temp")
dir |> getFiles

关于f# 检查目录是否可访问 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48328511/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com