0

Just a quick question here. Does anyone how can I set the access a difference server folder with username and password in c# .net?

I have have the following code to upload a file into a folder in the other server. Somehow I need to use the username and password then I can be only able to access into this folder. Does anyone know the code to set the access username and password for the folder?

   private void uploadFile()
   {

           DateTime dateTime = DateTime.Now;
           string sDate = dateTime.ToString("yyyyMMdd") + "_" + dateTime.ToString("fffffff");

           string fn = System.IO.Path.GetFileName(File1.PostedFile.FileName);

           string SaveLocation = Server.MapPath("document") + "\\" + sDate + "_" + fn;

           supportFileName = sDate + "_" + fn;

           try
           {
               File1.PostedFile.SaveAs(SaveLocation);
           }
           catch (Exception ex)
           {
               err.Text = "Error: " + ex.Message;
           }
   }
Jin Yong
  • 42,698
  • 72
  • 141
  • 187
  • http://stackoverflow.com/questions/10742661/c-sharp-accessing-active-directory-with-different-user-credentials – Freelancer May 02 '13 at 04:54

1 Answers1

2

for access the different server , and upload file into it. first, you need to give correct rights to this user account, and impersonation this account.

The term "Impersonation" in a programming context refers to a technique that executes the code under another user context than the user who originally started an application, i.e. the user context is temporarily changed once or multiple times during the execution of an application.

here are two article, hope can help you, with the sample codes:

http://www.codeproject.com/Articles/4051/Windows-Impersonation-using-C

http://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User

    using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )
{
   ...

   <code that executes under the new context>

   ...
}





 public WindowsImpersonationContext 
    ImpersonateUser(string sUsername, string sDomain, string sPassword)
{
    // initialize tokens
    IntPtr pExistingTokenHandle = new IntPtr(0);
    IntPtr pDuplicateTokenHandle = new IntPtr(0);
    pExistingTokenHandle = IntPtr.Zero;
    pDuplicateTokenHandle = IntPtr.Zero;

    // if domain name was blank, assume local machine
    if (sDomain == "")
        sDomain = System.Environment.MachineName;

    try
    {
        string sResult = null;

        const int LOGON32_PROVIDER_DEFAULT = 0;

        // create token
        const int LOGON32_LOGON_INTERACTIVE = 2;
        //const int SecurityImpersonation = 2;

        // get handle to token
        bool bImpersonated = LogonUser(sUsername, sDomain, sPassword, 
            LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, 
                ref pExistingTokenHandle);

        // did impersonation fail?
        if (false == bImpersonated)
        {
            int nErrorCode = Marshal.GetLastWin32Error();
            sResult = "LogonUser() failed with error code: " + 
                nErrorCode + "\r\n";

            // show the reason why LogonUser failed
            MessageBox.Show(this, sResult, "Error", 
                MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        // Get identity before impersonation
        sResult += "Before impersonation: " + 
            WindowsIdentity.GetCurrent().Name + "\r\n";

        bool bRetVal = DuplicateToken(pExistingTokenHandle, 
            (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, 
                ref pDuplicateTokenHandle);

        // did DuplicateToken fail?
        if (false == bRetVal)
        {
            int nErrorCode = Marshal.GetLastWin32Error();
            // close existing handle
            CloseHandle(pExistingTokenHandle); 
            sResult += "DuplicateToken() failed with error code: " 
                + nErrorCode + "\r\n";

            // show the reason why DuplicateToken failed
            MessageBox.Show(this, sResult, "Error", 
                MessageBoxButtons.OK, MessageBoxIcon.Error);
            return null;
        }
        else
        {
            // create new identity using new primary token
            WindowsIdentity newId = new WindowsIdentity
                                        (pDuplicateTokenHandle);
            WindowsImpersonationContext impersonatedUser = 
                                        newId.Impersonate();

            // check the identity after impersonation
            sResult += "After impersonation: " + 
                WindowsIdentity.GetCurrent().Name + "\r\n";

            MessageBox.Show(this, sResult, "Success", 
                MessageBoxButtons.OK, MessageBoxIcon.Information);
            return impersonatedUser;
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        // close handle(s)
        if (pExistingTokenHandle != IntPtr.Zero)
            CloseHandle(pExistingTokenHandle);
        if (pDuplicateTokenHandle != IntPtr.Zero) 
            CloseHandle(pDuplicateTokenHandle);
    }
}
Yan Zhao
  • 185
  • 1
  • 8