Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. Visual Basic
  4. Visual Basic program to recursively take ownership of a folder and all its sub-contents

Visual Basic program to recursively take ownership of a folder and all its sub-contents

Scheduled Pinned Locked Moved Visual Basic
helpcollaborationquestion
8 Posts 2 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • U Offline
    U Offline
    User 11833437
    wrote on last edited by
    #1

    I need to create a tool that will recursively take ownership of a folder for our helpdesk team, we logon with admin tokens to perform administrative tasks so anyone who uses this tool will only be IT personnel and will have local admin rights when they logon with their token. Users are losing data because of corrupt file synchronization. The only way we can retrieve it is to take ownership of the c:\windows\csc and its contents. This is a very short explanation of why I need a tool, the story is much longer but this lays out why I started this project. I am new to visual basic and programming. I wrote a program that will allow you to browse to the folder you want to take ownership of but I can't figure how get all the subdirectories. Can someone please help me make this program work recursively? Here is the main part of the code and this will take ownership on the parent directory eg. c:\test: #End Region Private Sub bnBrowseFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bnBrowseFolder.Click If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then Me.folderName.Text = FolderBrowserDialog1.SelectedPath End If End Sub Private Sub bnQuit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bnQuit.Click Me.Close() End Sub Private Sub bnDoit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bnDoit.Click If tbUserName.Text = "" Then MsgBox("Please type your NMEA account name (eg. Domain\adminaccountname)", MsgBoxStyle.Exclamation) Exit Sub End If strPath = folderName.Text For Each Folder In IO.Directory.GetDirectories(strPath, "*", IO.SearchOption.AllDirectories) Next strPath = folderName.Text strUser = tbUserName.Text Try ChangeOwner(strPath, strUser) Catch ex As Exception MsgBox("Error: " & ex.Message, MsgBoxStyle.Critical) End Try MsgBox("Done!") End Sub

    W 1 Reply Last reply
    0
    • U User 11833437

      I need to create a tool that will recursively take ownership of a folder for our helpdesk team, we logon with admin tokens to perform administrative tasks so anyone who uses this tool will only be IT personnel and will have local admin rights when they logon with their token. Users are losing data because of corrupt file synchronization. The only way we can retrieve it is to take ownership of the c:\windows\csc and its contents. This is a very short explanation of why I need a tool, the story is much longer but this lays out why I started this project. I am new to visual basic and programming. I wrote a program that will allow you to browse to the folder you want to take ownership of but I can't figure how get all the subdirectories. Can someone please help me make this program work recursively? Here is the main part of the code and this will take ownership on the parent directory eg. c:\test: #End Region Private Sub bnBrowseFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bnBrowseFolder.Click If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then Me.folderName.Text = FolderBrowserDialog1.SelectedPath End If End Sub Private Sub bnQuit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bnQuit.Click Me.Close() End Sub Private Sub bnDoit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bnDoit.Click If tbUserName.Text = "" Then MsgBox("Please type your NMEA account name (eg. Domain\adminaccountname)", MsgBoxStyle.Exclamation) Exit Sub End If strPath = folderName.Text For Each Folder In IO.Directory.GetDirectories(strPath, "*", IO.SearchOption.AllDirectories) Next strPath = folderName.Text strUser = tbUserName.Text Try ChangeOwner(strPath, strUser) Catch ex As Exception MsgBox("Error: " & ex.Message, MsgBoxStyle.Critical) End Try MsgBox("Done!") End Sub

      W Offline
      W Offline
      Wendelius
      wrote on last edited by
      #2

      You would need to create the method in a recursive way but before going to that, wouldn't it be easier to execute takeown using a new process? In other words something like

      Process.Start("takeown /F directoryname /R /A")

      For more info, see takeown[^]

      U 1 Reply Last reply
      0
      • W Wendelius

        You would need to create the method in a recursive way but before going to that, wouldn't it be easier to execute takeown using a new process? In other words something like

        Process.Start("takeown /F directoryname /R /A")

        For more info, see takeown[^]

        U Offline
        U Offline
        User 11833437
        wrote on last edited by
        #3

        It would be easier but I want to do it this first. Once I get this working I may do two more projects one with Takeown and one using WMI Win32_Directory TakeOwnershipEx Then test all 3 and see which one I like better. Takeown and WMI have been suggested to me but I really want to make this work first. I have used takeown a lot as well as icacls from the command line. How would I create the method in a recursive way? I have tried numerous way I have found numerous ways searching the internet but I can't do anything the right way. I even used the WMI Code Creator with elevated privileges and it fails even though I can take ownership of the parent directory with my tool. I am new to programming and I am learning but I need help.

        W 1 Reply Last reply
        0
        • U User 11833437

          It would be easier but I want to do it this first. Once I get this working I may do two more projects one with Takeown and one using WMI Win32_Directory TakeOwnershipEx Then test all 3 and see which one I like better. Takeown and WMI have been suggested to me but I really want to make this work first. I have used takeown a lot as well as icacls from the command line. How would I create the method in a recursive way? I have tried numerous way I have found numerous ways searching the internet but I can't do anything the right way. I even used the WMI Code Creator with elevated privileges and it fails even though I can take ownership of the parent directory with my tool. I am new to programming and I am learning but I need help.

          W Offline
          W Offline
          Wendelius
          wrote on last edited by
          #4

          If you want to create a recursive function you need to loop through the directories and for each directory call the same function again. Consider the following code:

          Sub HandleDir(directory As String)

            Try
               System.Diagnostics.Debug.WriteLine("I'm in directory " & directory)
               For Each subdir As String In System.IO.Directory.GetDirectories(directory)
                  HandleDir(subdir)
               Next subdir
            Catch exception As System.Exception
               System.Diagnostics.Debug.WriteLine(exception.Message)
            End Try
          

          End Sub

          You can try that by calling it for example like this

          HandleDir("C:\")

          That should list all the directories where you have access.

          U 1 Reply Last reply
          0
          • W Wendelius

            If you want to create a recursive function you need to loop through the directories and for each directory call the same function again. Consider the following code:

            Sub HandleDir(directory As String)

              Try
                 System.Diagnostics.Debug.WriteLine("I'm in directory " & directory)
                 For Each subdir As String In System.IO.Directory.GetDirectories(directory)
                    HandleDir(subdir)
                 Next subdir
              Catch exception As System.Exception
                 System.Diagnostics.Debug.WriteLine(exception.Message)
              End Try
            

            End Sub

            You can try that by calling it for example like this

            HandleDir("C:\")

            That should list all the directories where you have access.

            U Offline
            U Offline
            User 11833437
            wrote on last edited by
            #5

            once I add this how do I connect that with the part of the code that executes the change owner? Try ChangeOwner(strPath, strUser) Catch ex As Exception MsgBox("Error: " & ex.Message, MsgBoxStyle.Critical) End Try Would I change this to? Subdir = Me.FolderName.Text Try System.Diagnostics.Debug.WriteLine("I'm in directory " & directory) For Each subdir As String In System.IO.Directory.GetDirectories(directory) ChangeOwner(subdir, strUser) Next subdir Catch exception As System.Exception System.Diagnostics.Debug.WriteLine(exception.Message) End Try strpath comes from here: If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then Me.folderName.Text = FolderBrowserDialog1.SelectedPath End If I really appreciate your help by the way.

            W 1 Reply Last reply
            0
            • U User 11833437

              once I add this how do I connect that with the part of the code that executes the change owner? Try ChangeOwner(strPath, strUser) Catch ex As Exception MsgBox("Error: " & ex.Message, MsgBoxStyle.Critical) End Try Would I change this to? Subdir = Me.FolderName.Text Try System.Diagnostics.Debug.WriteLine("I'm in directory " & directory) For Each subdir As String In System.IO.Directory.GetDirectories(directory) ChangeOwner(subdir, strUser) Next subdir Catch exception As System.Exception System.Diagnostics.Debug.WriteLine(exception.Message) End Try strpath comes from here: If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then Me.folderName.Text = FolderBrowserDialog1.SelectedPath End If I really appreciate your help by the way.

              W Offline
              W Offline
              Wendelius
              wrote on last edited by
              #6

              Just put the code to change the ownership of a single directory in place of the debug.writeline. Or if you need to set the ownership before entering the directory, then inside the loop. Just remember to pas the user as a parameter For example

              Sub HandleDir(directory As String, userName as String)

              Try
              ChangeOwner(directory, userName)
              For Each subdir As String In System.IO.Directory.GetDirectories(directory)
              HandleDir(subdir, userName)
              Next subdir
              Catch exception As System.Exception
              System.Diagnostics.Debug.WriteLine(exception.Message)
              End Try
              End Sub

              And to call

              HandleDir(Me.folderName.Text, strUser)

              U 1 Reply Last reply
              0
              • W Wendelius

                Just put the code to change the ownership of a single directory in place of the debug.writeline. Or if you need to set the ownership before entering the directory, then inside the loop. Just remember to pas the user as a parameter For example

                Sub HandleDir(directory As String, userName as String)

                Try
                ChangeOwner(directory, userName)
                For Each subdir As String In System.IO.Directory.GetDirectories(directory)
                HandleDir(subdir, userName)
                Next subdir
                Catch exception As System.Exception
                System.Diagnostics.Debug.WriteLine(exception.Message)
                End Try
                End Sub

                And to call

                HandleDir(Me.folderName.Text, strUser)

                U Offline
                U Offline
                User 11833437
                wrote on last edited by
                #7

                Mika thank you so much for helping with this tool. Your suggestion was the difference. I was able to take ownership of only the parent directory at first. So I decided to try and implement recursive permissions first. I got that to work right away. So I put that piece of code at the of the same sub routine that I called the change of ownership and it worked on the first try after permissions were applied. I had ownership of every sub-directory and full control permissions. I have a few more tasks to implement but this was the major obstacle. Once again thank you very much.:thumbsup: Here is the code for the whole thing. Some of it is generated by visual studio express. I also used several examples I found on the internet and molded them into what I needed. 'CSC TAKE OWNERSHIP AND DATA RECOVERY TOOL 'This tools will recursively take ownership of the c:\windows\csc folder. Then copy the affected users 'folder and backup their user profile to a network share then remove all the folders under c:\windows\csc\v2.06\namespace and delete all user profiles. Imports System.IO Imports System Imports System.Drawing Imports System.Windows.Forms Imports System.Security.AccessControl Public Class Form1 Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() InitializeComponent() End Sub Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub Private components As System.ComponentModel.IContainer Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents FolderBrowserDialog1 As System.Windows.Forms.FolderBrowserDialog Friend WithEvents folderName As System.Windows.Forms.TextBox Friend WithEvents tbUserName As System.Windows.Forms.TextBox Friend WithEvents bnBrowseFolder As System.Windows.Forms.Button Friend WithEvents bnDoit As System.Windows.Forms.Button Friend WithEvents bnQuit As System.Windows.Forms.Button Friend WithEvents Label2 As Label Friend WithEvents PictureBox1 As PictureBox Friend WithEvents Label3 As Label Friend WithEvents LinkLabel1 As LinkLabel Friend WithEvents Label4 As System.Windows.Forms.Label Private Sub InitializeComponent() Dim resources As Sys

                W 1 Reply Last reply
                0
                • U User 11833437

                  Mika thank you so much for helping with this tool. Your suggestion was the difference. I was able to take ownership of only the parent directory at first. So I decided to try and implement recursive permissions first. I got that to work right away. So I put that piece of code at the of the same sub routine that I called the change of ownership and it worked on the first try after permissions were applied. I had ownership of every sub-directory and full control permissions. I have a few more tasks to implement but this was the major obstacle. Once again thank you very much.:thumbsup: Here is the code for the whole thing. Some of it is generated by visual studio express. I also used several examples I found on the internet and molded them into what I needed. 'CSC TAKE OWNERSHIP AND DATA RECOVERY TOOL 'This tools will recursively take ownership of the c:\windows\csc folder. Then copy the affected users 'folder and backup their user profile to a network share then remove all the folders under c:\windows\csc\v2.06\namespace and delete all user profiles. Imports System.IO Imports System Imports System.Drawing Imports System.Windows.Forms Imports System.Security.AccessControl Public Class Form1 Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() InitializeComponent() End Sub Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub Private components As System.ComponentModel.IContainer Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents FolderBrowserDialog1 As System.Windows.Forms.FolderBrowserDialog Friend WithEvents folderName As System.Windows.Forms.TextBox Friend WithEvents tbUserName As System.Windows.Forms.TextBox Friend WithEvents bnBrowseFolder As System.Windows.Forms.Button Friend WithEvents bnDoit As System.Windows.Forms.Button Friend WithEvents bnQuit As System.Windows.Forms.Button Friend WithEvents Label2 As Label Friend WithEvents PictureBox1 As PictureBox Friend WithEvents Label3 As Label Friend WithEvents LinkLabel1 As LinkLabel Friend WithEvents Label4 As System.Windows.Forms.Label Private Sub InitializeComponent() Dim resources As Sys

                  W Offline
                  W Offline
                  Wendelius
                  wrote on last edited by
                  #8

                  You're welcome, glad it helped :)

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups