获取VB.NET中文件的所有者

时间:2018-06-29 02:04:29

标签: vb.net

我想获取文件所有者时,在VB.NET中遇到错误。

这是我的代码。

Imports System.Security.AccessControl
Imports System.Security.Principal
Imports System.IO
Dim fi As FileInfo = New FileInfo("X:\Temp\aa.txt")
Dim fs As FileSecurity = fi.GetAccessControl
Dim myuser As IdentityReference = fs.GetOwner(GetType(NTAccount))
Dim username = myuser.Value.ToString

我得到了错误:

System.Security.Principal.IdentityNotMappedException was caught
HResult=-2146233087
Message=Unable to translate some or all of the recognition references。
Source=mscorlib
StackTrace:
 System.Security.Principal.SecurityIdentifier.Translate(IdentityReferenceCollection sourceSids, Type targetType, Boolean forceSuccess)
       in System.Security.Principal.SecurityIdentifier.Translate(Type targetType)
       in System.Security.AccessControl.ObjectSecurity.GetOwner(Type targetType)
       in Ts2.From1.Button1_Click(Object sender, EventArgs e) 於 D:\Ts3\Ts1\Form1.vb: row 292
  InnerException: 

1 个答案:

答案 0 :(得分:1)

ypu可以使用此按钮轻松获取文件或文件夹的所有者。

    Public Function GetFileOwner(ByVal fileName As String) As String
    Try
        Dim fi As New FileInfo(fileName)
        Dim fs As System.Security.AccessControl.FileSecurity = fi.GetAccessControl
        Dim owner As System.Security.Principal.NTAccount = CType(fs.GetOwner(GetType(System.Security.Principal.NTAccount)), System.Security.Principal.NTAccount)
        Return owner.ToString
    Catch ex As Exception
        Return ""
    End Try
End Function


Public Function GetDirOwner(ByVal fileName As String) As String
    Try
        Dim di As New DirectoryInfo(fileName)
        Dim ds As System.Security.AccessControl.DirectorySecurity = di.GetAccessControl
        Dim owner As System.Security.Principal.NTAccount = CType(ds.GetOwner(GetType(System.Security.Principal.NTAccount)), System.Security.Principal.NTAccount)
        Return owner.ToString
    Catch ex As Exception
        Return ""
    End Try
End Function