I have a remote PC's shared drive I am connecting to. Works fine if I use the PC name in the remote path, but not when I use the IP. Though if I copy and paste the path with the IP address in my explorer it works fine as well.
This is the calling code:
// '\\\\CAS-UP2\\Images' ---> Works Fine
// '\\\\169.254.199.149\\Images' ---> Doesn't Work
using (new ConnectToSharedFolder(networkPath, credentials))
{
// We succesfully connected
haveAccess = true;
}
This is the class code:
public class ConnectToSharedFolder : IDisposable
{
private readonly string _networkName;
//---------------------------------------------------------------------------
/// <summary>
/// Constructor
/// </summary>
public ConnectToSharedFolder(string networkName, NetworkCredential credentials)
{
_networkName = networkName;
var netResource = new NetResource
{
Scope = ResourceScope.GlobalNetwork,
ResourceType = ResourceType.Disk,
DisplayType = ResourceDisplaytype.Share,
RemoteName = networkName
};
var userName = string.IsNullOrEmpty(credentials.Domain)
? credentials.UserName
: string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);
var result = WNetAddConnection2(
netResource,
credentials.Password,
userName,
0);
if (result != 0)
{
throw new Win32Exception(result, "Error connecting to remote share");
}
}
//---------------------------------------------------------------------------
/// <summary>
/// Deconstructor
/// </summary>
~ConnectToSharedFolder()
{
Dispose(false);
}
//---------------------------------------------------------------------------
/// <summary>
/// Dispose Method
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
//---------------------------------------------------------------------------
/// <summary>
/// Dispose Method
/// </summary>
protected virtual void Dispose(bool disposing)
{
WNetCancelConnection2(_networkName, 0, true);
}
//---------------------------------------------------------------------------
/// <summary>
/// WNet add connection method
/// </summary>
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2(NetResource netResource,
string password, string username, int flags);
//---------------------------------------------------------------------------
/// <summary>
/// WNet cancel connection method
/// </summary>
[DllImport("mpr.dll")]
private static extern int WNetCancelConnection2(string name, int flags,
bool force);
}