0

I have a problem creating folders in a shared folder password, when creating the folder with methods in the the System.IO namespace.

Example:

CreateDirectory(@"\\host\shared_folder\new_folder");

This gives me an error:

Logon Failure: unknown user name or bad password.

As the host has username and password, can you tell me if it is possible to insert the username and password to create the folder using methods in this namespace?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179

2 Answers2

1

You should be able to utilize the WindowsIdentity.Impersonate method to impersonate the account that has permissions to create the folder on the file share. The following contains sample code:

WindowsIdentity.Impersonate

EDIT: Using the sample code from the link above, you can put the CreateDirectory call in the following block of code:

using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle()))
{
    // Create Directory Here

    // Check the identity.
    Console.WriteLine("After impersonation: "
                        + WindowsIdentity.GetCurrent().Name);
}
jasonnissen
  • 156
  • 5
  • do you tell me create the folder with that code: using (var impersonation = new ImpersonatedUser(decryptedUser, decryptedDomain, decryptedPassword)) { Directory.CreateDirectory(newPath); } – user3059348 Dec 03 '13 at 01:09
  • Updated the answer to show where to place the call to create the directory. – jasonnissen Dec 03 '13 at 03:41
1

The application calling your library must be started with an identity which has the permissions required to create the folder, alternatively you can try and change the identity of the thread calling your code as follows...

Set Identity of Thread

You'll need to consider the ramifications of doing that. You should probably do this in a worker thread.

The permissions required is another matter. If it is a file share there are two sets of permissions to consider - the permissions for the file share and the file permissions DACLS on the folders in the file system.

Community
  • 1
  • 1
Mick
  • 6,527
  • 4
  • 52
  • 67