gpt4 book ai didi

vb.net - 在处理之前测试我是否对 VB .NET 4.5 中的文件具有完全读/写访问权限

转载 作者:行者123 更新时间:2023-12-04 04:45:44 25 4
gpt4 key购买 nike

我正在编写一个作为本地系统帐户运行的 Windows 服务。我试图确定我是否对开始进一步处理的文件具有完全读/写访问权限。这是我的代码:

    Dim FullPath As String
FullPath = "C:\directory\file.txt"
Dim ps As Security.PermissionSet
ps = New Security.PermissionSet(Security.Permissions.PermissionState.Unrestricted)
ps.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.FileIOPermissionAccess.AllAccess, FullPath))
ps.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.FileIOPermissionAccess.AllAccess, IO.Path.GetDirectoryName(FullPath)))
Try
ps.Demand()
Catch ex As Security.SecurityException
System.Diagnostics.EventLog.WriteEntry("ShopLink", "File " + FullPath + " will not be parsed. " + ex.Message)
Exit Sub
Catch ex As Exception
System.Diagnostics.EventLog.WriteEntry("ShopLink", "File " + FullPath + " will not be parsed. " + ex.Message)
Exit Sub
End Try

然后,我将文件的完全访问权限设置为我的服务运行所使用的用户帐户的“拒绝”。执行后,上面的代码不会抛出任何异常并允许开始处理文件。当服务稍后尝试更改和/或删除文件时,我收到“拒绝访问”异常。

有什么建议吗?

最佳答案

为此,我使用了这个小函数:

  Private Function HasAccess(ByVal ltFullPath As String)
Try
Using inputstreamreader As New StreamReader(ltFullPath)
inputstreamreader.Close()
End Using
Using inputStream As FileStream = File.Open(ltFullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
inputStream.Close()
Return True
End Using
Catch ex As Exception
Return False
End Try
End Function

在你的情况下:
If HasAccess(FullPath) ...

关于vb.net - 在处理之前测试我是否对 VB .NET 4.5 中的文件具有完全读/写访问权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18220170/

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