Get the owner of a file in VB.NET


Get the owner of a file in VB.NET



I have encountered a error in VB.NET when I want to get the owner of a file.



This is my code.


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



and I got error:


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:Ts3Ts1Form1.vb: row 292
InnerException:





Do these help ? blogs.msdn.microsoft.com/winsdk/2013/12/18/… or stackoverflow.com/questions/3324831/identitynotmappedexception
– Andrew Mortimer
2 days ago





yes,It's about AccountName...I change the computer to the same Domain,then, It's run!
– eason
2 days ago





That is a pretty normal mishap with mapped drive letters like X: You may well find an owner whose name is not known to your local OS. Ultimately it is a network configuration problem, domains are important.
– Hans Passant
2 days ago




1 Answer
1



ypu can easily get the owner of a file or folder using this ...


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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Export result set on Dbeaver to CSV