Used the below piece of code to access shared path with username and password :
The below piece of code can be invoked from another class by using the simple syntax as stated below :
UNCAccess unc = new UNCAccess(ConfigurationSettings.AppSettings["SharedPath"].ToString(), ConfigurationSettings.AppSettings["SharedPathUser"].ToString(), ConfigurationSettings.AppSettings["SharedPathDomain"].ToString(), ConfigurationSettings.AppSettings["SharedPathPassword"].ToString());
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Runtime.InteropServices;
public class UNCAccess
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct USE_INFO_2
{
internal String ui2_local;
internal String ui2_remote;
internal String ui2_password;
internal UInt32 ui2_status;
internal UInt32 ui2_asg_type;
internal UInt32 ui2_refcount;
internal UInt32 ui2_usecount;
internal String ui2_username;
internal String ui2_domainname;
}
[DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern UInt32 NetUseAdd(
String UncServerName,
UInt32 Level,
ref USE_INFO_2 Buf,
out UInt32 ParmError);
private string sUNCPath;
private string sUser;
private string sPassword;
private string sDomain;
private int iLastError;
public UNCAccess()
{
}
public UNCAccess(string UNCPath, string User, string Domain, string Password)
{
login(UNCPath, User, Domain, Password);
}
public int LastError
{
get { return iLastError; }
}
public bool login(string UNCPath, string User, string Domain, string Password)
{
sUNCPath = UNCPath;
sUser = User;
sPassword = Password;
sDomain = Domain;
return NetUseWithCredentials();
}
private bool NetUseWithCredentials()
{
uint returncode;
try
{
USE_INFO_2 useinfo = new USE_INFO_2();
useinfo.ui2_remote = sUNCPath;
useinfo.ui2_username = sUser;
useinfo.ui2_domainname = sDomain;
useinfo.ui2_password = sPassword;
useinfo.ui2_asg_type = 0;
useinfo.ui2_usecount = 1;
uint paramErrorIndex;
returncode = NetUseAdd(null, 2, ref useinfo, out paramErrorIndex);
iLastError = (int)returncode;
return returncode == 0;
}
catch
{
iLastError = Marshal.GetLastWin32Error();
return false;
}
}
}