NTFS File Owner in VB.net
Posted by daniel | Posted in Code Snippets | Posted on 26-11-2009
Tags: NTFS, owner, VB.net
2
Here is some VB.net 2005 code to set an NTFS file\folder owner:
For both of these you need to add:
Imports System.Security.AccessControl Imports System.Security.Principal Private Sub setOwner(ByRef FileName As String, ByRef account As NTAccount) Try Dim dInfo As New DirectoryInfo(FileName) Dim dir As New DirectorySecurity(FileName, AccessControlSections.None) End Sub dir.SetOwner(account) dInfo.SetAccessControl(dir) dir = Nothing dInfo = Nothing If System.IO.Directory.Exists(FileName) Then Dim Files As String() Files = Directory.GetFileSystemEntries(FileName) For Each element As String In Files setOwner(element, account) Next End If Catch ex As Exception Throw New Exception(ex.Message.ToString()) End Try End Function
Here is how to get an owner:
Private Function GetOwner(ByVal Path As String) As String Try Dim User As System.Security.Principal.NTAccount = DirectCast( _ System.IO.File.GetAccessControl(Path). _ GetOwner(GetType( _ System.Security.Principal.NTAccount)), _ System.Security.Principal.NTAccount) Return User.Value End Function
My next post will be looking at viewing\setting \removing NTFS permissions…. so keep an eye out!




The end sub on line 9 is wrong and surley the end function should also be an end sub..?
It does look like something has gone wierd when I put the link up. I know this has worked in the past, because i am using it. But yes it is wrong. I will copy it again later and make sure nothing wierd happens this time.
Thanks for pointing it out Mark.