C# - WNetAddConnection2"the network name cannot be found"
I was wondering if anyone could help me out – I'm a C# newbie; thank you
greatly in advance for any and all help/advice!
Goal: - Make a UNC connection to a remote Windows server that lives in a
different trusted domain (I'm in domain_A, and I make a UNC connection to
a server in trusted domain_B). - Pass in the user id (domain\user_id) and
password as part of the UNC/drive mapping process.
I've been struggling with pinvoke/WNetAddConnection2.
When I run my console app, I get a Win32Exception "the network name cannot
be found".
I've pulled code samples from stackoverflow, MSDN, and elsewhere on the
web, but I'm still stuck.
Again, thank you so much for any help, advice, etc. :-)
This is the WNetAddConnection2 and NETRESOURCE stuff...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.ComponentModel;
namespace backup_log_checker
{
static class Remote_Connection
{
//////////////////////////////////////////////
internal static string server_name = null;
internal static string unc_path_front = @"\\";
internal static string unc_path_end = @"\test_share";
internal static string unc_full_path = null;
internal static string user_name = null;
internal static string password = null;
//////////////////////////////////////////////
private enum ResourceScope
{
RESOURCE_CONNECTED = 1,
RESOURCE_GLOBALNET,
RESOURCE_REMEMBERED,
//RESOURCE_RECENT,
//RESOURCE_CONTEXT
}
private enum ResourceType
{
RESOURCETYPE_ANY,
RESOURCETYPE_DISK,
RESOURCETYPE_PRINT,
//RESOURCETYPE_RESERVED
}
private enum ResourceUsage
{
RESOURCEUSAGE_CONNECTABLE = 0x00000001,
RESOURCEUSAGE_CONTAINER = 0x00000002,
RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004,
RESOURCEUSAGE_SIBLING = 0x00000008,
RESOURCEUSAGE_ATTACHED = 0x00000010
}
private enum ResourceDisplayType
{
RESOURCEDISPLAYTYPE_GENERIC,
RESOURCEDISPLAYTYPE_DOMAIN,
RESOURCEDISPLAYTYPE_SERVER,
RESOURCEDISPLAYTYPE_SHARE,
RESOURCEDISPLAYTYPE_FILE,
RESOURCEDISPLAYTYPE_GROUP,
RESOURCEDISPLAYTYPE_NETWORK,
RESOURCEDISPLAYTYPE_ROOT,
RESOURCEDISPLAYTYPE_SHAREADMIN,
RESOURCEDISPLAYTYPE_DIRECTORY,
RESOURCEDISPLAYTYPE_TREE,
RESOURCEDISPLAYTYPE_NDSCONTAINER
}
[StructLayout(LayoutKind.Sequential)]
private struct NETRESOURCE
{
public ResourceScope oResourceScope;
public ResourceType oResourceType;
public ResourceDisplayType oDisplayType;
public ResourceUsage oResourceUsage;
public string sLocalName;
public string sRemoteName;
public string sComments;
public string sProvider;
}
[DllImport("mpr.dll", CharSet=CharSet.Unicode)]
private static extern int WNetAddConnection2
(ref NETRESOURCE oNetworkResource, string sPassword,
string sUserName, int iFlags);
[DllImport("mpr.dll", CharSet=CharSet.Unicode)]
private static extern int WNetCancelConnection2
(string sLocalName, uint iFlags, int iForce);
//////////////////////////////////////////////
public static string unc_connection(string s)
{
string[] myarray = { unc_path_front, server_name,
unc_path_end };
string uncFullPath = String.Concat(myarray[0], myarray[1],
myarray[2]);
Console.WriteLine("test unc path: {0}", uncFullPath);
return uncFullPath;
}
//////////////////////////////////////////////
public static bool MapNetworkDrive()
{
//Checks if the last character is "\" as this causes error
on mapping a drive.
if (unc_full_path.Substring(unc_full_path.Length - 1, 1)
== @"\")
{
unc_full_path = unc_full_path.Substring(0,
unc_full_path.Length - 1);
}
//create a new instance of the NETRESOURCE struct
string sDriveLetter = "z";
NETRESOURCE myNetworkResource = new NETRESOURCE();
myNetworkResource.oResourceScope =
ResourceScope.RESOURCE_CONNECTED;
myNetworkResource.oResourceType =
ResourceType.RESOURCETYPE_DISK;
myNetworkResource.oDisplayType =
ResourceDisplayType.RESOURCEDISPLAYTYPE_SHARE;
myNetworkResource.sLocalName = null;
myNetworkResource.sRemoteName = unc_full_path;
myNetworkResource.sProvider = null;
myNetworkResource.sLocalName = sDriveLetter + ":";
//If Drive is already mapped disconnect the current
//mapping before adding the new mapping
if (IsDriveMapped(sDriveLetter))
{
DisconnectNetworkDrive(sDriveLetter, true);
}
//Actually make the network connection
int result = WNetAddConnection2(ref myNetworkResource,
password, user_name, 0);
if (!result.Equals(0))
{
throw new Win32Exception((int)result);
}
return true;
}
public static int DisconnectNetworkDrive(string sDriveLetter,
bool bForceDisconnect)
{
if (bForceDisconnect)
{
return WNetCancelConnection2(sDriveLetter + ":", 0, 1);
}
else
{
return WNetCancelConnection2(sDriveLetter + ":", 0, 0);
}
}
public static bool IsDriveMapped(string sDriveLetter)
{
string[] DriveList = Environment.GetLogicalDrives();
for (int i = 0; i < DriveList.Length; i++)
{
if (unc_full_path == DriveList[i].ToString())
{
return true;
}
}
return false;
}
}
}
This is my "Main.cs" driver class...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.ComponentModel;
namespace backup_log_checker
{
class Program
{
static void Main(string[] args)
{
//take in server name
Console.WriteLine("Enter the Store System Name: ");
Remote_Connection.server_name = Console.ReadLine();
//create unc path
Remote_Connection.unc_full_path =
Remote_Connection.unc_connection(Remote_Connection.server_name);
Console.WriteLine(@"Connecting to this UNC path: {0}",
Remote_Connection.unc_full_path);
//take in user ID
Console.WriteLine(@"Enter you RETAIL user name (ex:
CORP\my_user_ID): ");
Remote_Connection.user_name = Console.ReadLine();
//take in and mask the password
string pass = null;
Console.WriteLine("Enter your password: ");
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
// Backspace Should Not Work
if (key.Key != ConsoleKey.Backspace)
{
pass += key.KeyChar;
Console.Write("*");
}
else
{
pass = pass.Remove(pass.Length - 1);
Console.Write("\b \b");
}
}
// Stops Receving Keys Once Enter is Pressed
while (key.Key != ConsoleKey.Enter);
Remote_Connection.password = pass;
Console.WriteLine();
//actually map and create the unc path
Remote_Connection.MapNetworkDrive();
//Find_BackupFile.verify_filesExist();
//Remote_Connection.DisconnectNetworkDrive(Remote_Connection.uncFullPath,
false);
}
}
}
No comments:
Post a Comment