Create a Directory on network Shared Drive impersonating a service account using C# asp.net

How can I Create a Directory on network Shared Drive impersonating a service account using C# asp.net. My web.config identity impersonate tag is set to true and no username and password is provided for security reasons. So I am just impersonating the code where I am accessing the network resources. It would be great if I could get a working code. Thanks.
nk_kanikaramAsked:
Who is Participating?
 
nk_kanikaramConnect With a Mentor Author Commented:
looks like its working now. I am using the code below. No need to set the permissions for the impersonation user on the root folder. Looks like the code adds the impersonating user to the newly created folder's security tab users list but with no permissions set for this user on the folder.

        string tempRoot = @"\\serverName\ExistingFolderwithpermissions\NewFolder";
        if (LogonUser("userName", "userDomain", "userPassword",
            8, // LOGON32_LOGON_NETWORK_CLEARTEXT    
            0, // LOGON32_PROVIDER_DEFAULT    
            out token))
        {
            wi = new WindowsIdentity(token);
            WindowsImpersonationContext wic = wi.Impersonate();
            try
            {
                Directory.CreateDirectory(tempRoot);
            }
            catch (UnauthorizedAccessException uae)
            {
                string msg = uae.StackTrace;
            }
            wic.Undo();
            CloseHandle(token);
        }
        else
        {
        }
0
 
TechTiger007Commented:
Here is a sample that moves file from one path to another, you can build on the same code to create directory in network path

http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_2.0/Q_23120865.html?sfQueryTermInfo=1+creat+folder+imperson
0
 
nk_kanikaramAuthor Commented:
Could I please get the C# equivalent code for the same.
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
TechTiger007Connect With a Mentor Commented:
Here is a sample in C#.
The full source code is available as zip file download it and use the required part of the code

http://csharptuning.blogspot.com/2007/06/impersonation-in-c.html
0
 
nk_kanikaramAuthor Commented:
Thanks for the response. I am doing the following, but still i am getting the Access denied error message.I have looked at the folder security and granted fullcontrol to the root folder underwhich i am trying to create the new folder. Am I missing something here.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using System.IO;

public partial class RunAs_Impersonator : System.Web.UI.Page
{
    public const int LOGON32_LOGON_INTERACTIVE = 2;
    public const int LOGON32_PROVIDER_DEFAULT = 0;
    IntPtr tokenHandle;
    IntPtr dupeTokenHandle;
    WindowsImpersonationContext impersonatedUser;

    [DllImport("advapi32.dll")]
    public static extern int LogonUserA(String lpszUserName,
        String lpszDomain,
        String lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        ref IntPtr phToken);
    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int DuplicateToken(IntPtr hToken,
        int impersonationLevel,
        ref IntPtr hNewToken);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern bool RevertToSelf();

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern bool CloseHandle(IntPtr handle);

    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    public void ImpersonateStart(string Domain, string userName, string Password)
    {
        try
        {
            tokenHandle = IntPtr.Zero;
            int returnValue = LogonUserA(userName, Domain, Password, 2, 0, ref tokenHandle);
            if (returnValue == 0)
            {
                int ret = Marshal.GetLastWin32Error();
                throw new System.ComponentModel.Win32Exception(ret);
            }
            WindowsIdentity newId = new WindowsIdentity(tokenHandle);
            impersonatedUser = newId.Impersonate();
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }

    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    public void ImpersonateStop()
    {
        impersonatedUser.Undo();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            ImpersonateStart("userDomain", "userName", "userPassword");
            if (Directory.Exists(@"\\serverName\ExistingFolderwithpermissions"))// the "userName" account has modify permissions on this folder
            {
                //This line of code throws exception "Access denied to the \\serverName\ExistingFolderwithpermissions\NewFolder path."
                Directory.CreateDirectory(@"\\serverName\ExistingFolderwithpermissions\NewFolder");
            }
            ImpersonateStop();
        }
        catch (Exception ex)
        {
            ImpersonateStop();
        }
    }
}
0
 
TechTiger007Commented:
does this user id that you are using to impersonate have permission on the folder?

is impersonation successful? did it throw any exception?

0
 
nk_kanikaramAuthor Commented:
Yes, the user has access to @"\\serverName\ExistingFolderwithpermissions". The code passed the impersonation. But fails on Creating the directory. Just for testing purposes, I replaced the CreateDirectory Code with following to view files under the same root folder and had no issues viewing the files.

            ImpersonateStart("userDomain", "userName", "userPassword");
            DirectoryInfo dirInfo = new DirectoryInfo(@"\\serverName\ExistingFolderwithpermissions");
            FileInfo[] files = dirInfo.GetFiles();
            DirectoryInfo[] directories = dirInfo.GetDirectories();
            foreach (DirectoryInfo dir in directories)
            {
                Response.Write(dir.FullName + "<br/>");
            }
            foreach (FileInfo file in files)
            {
                Response.Write(file.FullName + "<br/>");
            }
           ImpersonateStop();
0
 
TechTiger007Connect With a Mentor Commented:
If you are able to see the list of files that means the user have got read access to the folder. To create another folder user should have "Modify" privilege on it having "Write" privilege wont be enough. Does the user have Modify privilege on the folder?

Try out with giving full access for the user if Modify didnt work.
0
 
nk_kanikaramAuthor Commented:
The user has full control, read & execute, modify, write permissions on the folder. Also, I have checked all of the advanced permissions for this user on the folder(like create files, folders, write, append data etc.) . And also made sure that the folder is shared.
0
 
TechTiger007Connect With a Mentor Commented:
Let me confirm
1. User has got modify permission on the physical folder of the shared folder on the machine
2. User has got full access on the share permissions. (folder permissions and share permissions are different)
3. Both machines are in same domain
4. User is part of the domain
5. User impersonation succeeds

above are conditions that should satisfy.
I think we did not check the permission for user in the share. what do you say?
0
 
nk_kanikaramAuthor Commented:
Yes, I have double checked all the 5 points mentioned, all the permissions are set for the user on the shared folder, user is part of the domain, impersonation succeeds, machines are in the same domain etc.,
I Tried to run the same code from the server itself and surprisingly it failed even on the server.
Seems like Directory.CreateDirectory(@"\\serverName\ExistingFolderwithpermissions\NewFolder"); fails with UNC path. Same code works fine with physical path. ie Directory.CreateDirectory(@"C:\ExistingFolderwithpermissions\NewFolder");

0
 
TechTiger007Connect With a Mentor Commented:
try to impersonate with your user account once and check if you are able to create folder

may be I am asking again but just to confirm, is this what you did?
Right click on the folder that is shared
Select "Share and Security" option or "Share" option (depends on the OS)
In the pop up window, select security tab
click on permissions
give full permission for the user

0
 
TechTiger007Commented:
Thats good to hear.
0
 
nk_kanikaramAuthor Commented:
Thanks a ton for your help.
0
 
TechTiger007Commented:
You are welcome :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.