Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 1.55 KB  |  hits: 22  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Creating Windows Folders using impersonation
  2. //set the cursor
  3.  
  4. string activeDir = "\\department\shares\users\";
  5.  
  6. //create directory with userID as the folder name
  7.  
  8. string newPath = System.IO.Path.Combine(activeDir + userID);
  9.  
  10. System.IO.Directory.CreateDirectory(newPath);
  11.        
  12. using (var impersonation = new ImpersonatedUser(decryptedUser, decryptedDomain, decryptedPassword))
  13. {
  14.   Directory.CreateDirectory(newPath);
  15. }
  16.        
  17. public class WNet
  18. {
  19.     public static void AddConnection(string resource, string username, string password)
  20.     {
  21.         NETRESOURCE nr = new NETRESOURCE();
  22.         nr.RemoteName = resource;
  23.         uint err = WNetAddConnection2W(ref nr, password, username, 0);
  24.         if (err != 0)
  25.             throw new RemoteDirectoryException(string.Format("WNetAddConnection2 failed with error: #{0}", err));
  26.     }
  27.  
  28.     private struct NETRESOURCE
  29.     {
  30.         public uint Scope;
  31.         public uint Type;
  32.         public uint DisplayType;
  33.         public uint Usage;
  34.         public string LocalName;
  35.         public string RemoteName;
  36.         public string Comment;
  37.         public string Provider;
  38.     }
  39.  
  40.     [DllImport("mpr.dll", CharSet = CharSet.Unicode)]
  41.     private extern static uint WNetAddConnection2W(ref NETRESOURCE lpNetResource, string lpPassword, string lpUsername, uint dwFlags);
  42. }
  43.        
  44. string activeDir = "\\department\shares\users\";
  45. string username = "username";
  46. string password = "password";
  47.  
  48. WNet.AddConnection(activeDir, username, password);
  49.  
  50. string newPath = System.IO.Path.Combine(activeDir, userID);
  51. System.IO.Directory.CreateDirectory(newPath);