How I validate UNC Connection

Dani_S 3,226 Reputation points
2024-07-09T10:29:56.7866667+00:00

Hi,

When I supply bad domain i get success instead of failure ?, why ?

public static bool IsUncConnectionValid(string directoryName, string uncDomain, string userName, string password)

{

   UncHelper uncHelper = null;

   try

   {  

       if(string.IsNullOrEmpty(directoryName) || string.IsNullOrEmpty(uncDomain) || string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))

       {

           return false;

       }

       //if (!(Uri.CheckHostName(uncDomain) != UriHostNameType.Unknown))

       //{

       //    return false;

       //}

       uncHelper = new UncHelper(directoryName, userName, password, uncDomain);

       uint uncResult = uncHelper.Connect();

       if (!uncHelper.IsConnected)

       {

           return false;

       }

   }

   catch (Exception ex)

   {

       _logger.Error("UNC connection is not valid", ex);

   }

   finally

   {   

       if (uncHelper != null)

       { 

           uncHelper.Dispose();

       }


       

   }

   return true;
   }

public class UncHelper :  IDisposable

{

cpp
private static AppLogManager _logger = AppLogManager.GetLogger<UncHelper>();

public bool IsConnected { get; set;}

private string _userName = "";

private string _password = "";

private string _uncPath = "";

private string _domain = "";



[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]

internal struct USE_INFO_2

{

    internal LPWSTR ui2_local;

    internal LPWSTR ui2_remote;

    internal LPWSTR ui2_password;

    internal DWORD ui2_status;

    internal DWORD ui2_asg_type;

    internal DWORD ui2_refcount;

    internal DWORD ui2_usecount;

    internal LPWSTR ui2_username;

    internal LPWSTR ui2_domainname;

}

[DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]

internal static extern NET_API_STATUS NetUseAdd(LPWSTR UncServerName, DWORD Level, ref USE_INFO_2 Buf, out DWORD ParmError);

[DllImport("NetApi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]

internal static extern NET_API_STATUS NetUseDel(LPWSTR UncServerName, LPWSTR UseName, DWORD ForceCond);

[DllImport("advapi32.dll", SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)]

[return: MarshalAs(UnmanagedType.Bool)]

public static extern bool LogonUser(

  [MarshalAs(UnmanagedType.LPStr)] string pszUserName,

  [MarshalAs(UnmanagedType.LPStr)] string pszDomain,

  [MarshalAs(UnmanagedType.LPStr)] string pszPassword,

  int dwLogonType,

  int dwLogonProvider,

  ref IntPtr phToken);

public UncHelper(string uncPath, string userName = "", string password = "", string domain = "")

{

    try

    {

        _uncPath = uncPath;

        _userName = userName;

        _password = password;

         _domain = domain;

    }

    catch (Exception ex)

    {

       _logger.Error("UncHelper has crashed: ", ex);

    }

}

/// <summary>

/// Connect to unc path by domain, user and pwaaword

/// </summary>

/// <returns>The function return the results of connection(succcess 0 or 1219) other vaue it false</returns>

public uint Connect()

{

    uint uiRes;

    try

    {

        USE_INFO_2 useinfo = new USE_INFO_2();

        useinfo.ui2_remote = _uncPath;

        useinfo.ui2_username = _userName;

        useinfo.ui2_domainname = _domain;

        useinfo.ui2_password = _password;

        useinfo.ui2_asg_type = 0;

        useinfo.ui2_usecount = 1;//100

        uint paramErrorIndex;

        uiRes = NetUseAdd(null, 2, ref useinfo, out paramErrorIndex);

         if (uiRes == (uint)0 )//|| uiRes == (uint)1219)

        {

            IsConnected = true;

        }

        else

        {

            IsConnected = false;

        }

    }

    catch (Exception ex)

    {

        _logger.Error("Unc helper has crashed: ", ex);

        uiRes = 1;

        IsConnected = false;

    }

    return uiRes;

}



// Delete the unc conection

private int NetUseDelete()

{

    int nRes;

    try

    {

        nRes = (int)NetUseDel(null, _uncPath, 2);

    }

    catch (Exception ex)

    {

        nRes = Marshal.GetLastWin32Error();

        _logger.Error($"UncHelper.NetUseDelete   Error: {nRes.ToString()} Error description:{UncErrorCode.GetSystemMessage(nRes)} has crashed: ", ex);

    }

    return nRes;

}



public void Dispose()

{

    try

    {

        Dispose(true);

     }

    catch (Exception ex)

    {

        _logger.Error("UncHelper.Dispose() has Crashed: ", ex);

    }

    finally

    {

        GC.SuppressFinalize(this);

    }

}

 public virtual void Dispose(bool disposing)

{

    try

    { 

            NetUseDelete();

            IsConnected = false;


       

     }

    catch (Exception ex)

    {

        _logger.Error("UncHelper.Dispose(bool disposing) has Crashed: ", ex);

        IsConnected = false;

    }

}


 

~UncHelper()

{

    Dispose(false);

}
}

Thanks,

![User's image](/api/attachments/bbc61d9d-55cc-4707-90d8-3979b3f9d29e?platform=QnA)

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,582 questions
{count} votes