Tuesday, June 10, 2014

C#.NET - Accessing Share folder files with Network Authentication

Purpose :

Accessing Share folder files with Network Authentication

Step 1 : Create a class named SoddingNetworkAuth

Class Name : SoddingNetworkAuth.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
public class NetworkAuth : IDisposable
{
    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
    [DllImport("kernel32", SetLastError = true)]
    private static extern bool CloseHandle(IntPtr hObject);
    private IntPtr userHandle = IntPtr.Zero;
    private WindowsImpersonationContext impersonationContext;
    public NetworkAuth(string user, string domain, string password)
    {
        try
        {
            if (!string.IsNullOrEmpty(user))
            {
                // Call LogonUser to get a token for the user 
                bool loggedOn = LogonUser(user, domain, password,
                 9 /*(int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS*/,
                 3 /*(int)LogonProvider.LOGON32_PROVIDER_WINNT50*/,
                out userHandle);
                if (!loggedOn)
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                // Begin impersonating the user 
                impersonationContext = WindowsIdentity.Impersonate(userHandle);
            }
        }
        catch (Exception ex)
        {
            ExceptionHandler.HandleException(ex.ToString());
        }
    }
    public void Dispose()
    {
        try
        {
            if (userHandle != IntPtr.Zero)
                CloseHandle(userHandle);
            if (impersonationContext != null)
                impersonationContext.Undo();
        }
        catch (Exception ex)
        {
            ExceptionHandler.HandleException(ex.ToString());
        }
    }
}


Step 2 : Place it anywhere inside the form and use this below code to copy file

#region "File copying with NetworkAuth "
using (new NetworkAuth("sShareFolder_Username","sShareFolderName", "sShareFolder_Password"))
{
      try
            {
                /* This is for checking voice file details */
                if (!File.Exists("GiveFilePath"))
                {
                    File.Copy("SourcePath", "DestinationPath", true);
                }
            }
            catch (Exception ex)
            {
            }
}   


4 comments:

  1. Good Article.It will be helpful for people like me

    ReplyDelete
  2. Great article. It will be helpful for people like Ismail

    ReplyDelete
  3. Great article.
    Thanks it saved me a lot tym f searching.

    ReplyDelete
  4. Thanks a lot.u helped a lot.

    ReplyDelete