Upload file on other system in the network

This Code snippet will help us to upload file on any system other than application server.

Suppose we have separate file and application server then this code will help us to upload image on file server from application server.

Following Namespaces needs to add to upload file:
using System.Security.Principal;
using System.Runtime.InteropServices;



Summary description for FileHandler
public class FileHandler
{
public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;

WindowsImpersonationContext impersonationContext;

//Programatically Add Service to Get Token
[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)]

//Programatically Add Service to Check for Duplicate Token
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);

//RevertToSelf terminates the impersonation of a client application.
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();

//Programatically Add Service to Terminate Process
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);


This method is used to get the token privilege for a valid user
public bool impersonateValidUser()
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;

if (RevertToSelf())
{

if (LogonUserA(ConfigurationManager.AppSettings["DomainUser"].ToString(), ConfigurationManager.AppSettings["Domain"].ToString(), ConfigurationManager.AppSettings["DomainPassword"].ToString(), LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}


Method to Upload file on network path. parameter of this functions are:
fileuploadcontrol as reference type, Destination Path as string.
impersonateValidUser() method is used to get the token for a valid user.
once we got the token we can save image on other system.

public Boolean UploadFile(ref FileUpload flUpload,string NetworkPath)
{
if (impersonateValidUser())
{
flUpload.SaveAs(NetworkPath + flUpload.FileName);
return true;
}
else
{
return false;
}
}
}

0 comments: