How I validate UNC Connection

Dani_S 3,786 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


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

1 answer

Sort by: Most helpful
  1. Jiale Xue - MSFT 46,556 Reputation points Microsoft Vendor
    2024-07-10T04:25:43.8466667+00:00

    Hi @Dani_S , Welcome to Microsoft Q&A, Proper Exception Handling: Ensure exception handling provides detailed information. Logging Enhancements: Improve logging for better traceability. Resource Management: Ensure resources are properly managed and disposed.

    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;
            }
    
            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);
            return false;
        }
        finally
        {   
            uncHelper?.Dispose();
        }
    
        return true;
    }
    
    public class UncHelper : IDisposable
    {
        private static AppLogManager _logger = AppLogManager.GetLogger<UncHelper>();
    
        public bool IsConnected { get; private set; }
    
        private readonly string _userName;
        private readonly string _password;
        private readonly string _uncPath;
        private readonly 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 = "")
        {
            _uncPath = uncPath;
            _userName = userName;
            _password = password;
            _domain = domain;
        }
    
        /// <summary>
        /// Connect to UNC path by domain, user, and password
        /// </summary>
        /// <returns>The function returns the result of the connection (success 0 or 1219), otherwise it returns false</returns>
        public uint Connect()
        {
            uint uiRes;
            try
            {
                USE_INFO_2 useinfo = new USE_INFO_2
                {
                    ui2_remote = _uncPath,
                    ui2_username = _userName,
                    ui2_domainname = _domain,
                    ui2_password = _password,
                    ui2_asg_type = 0,
                    ui2_usecount = 1
                };
                uint paramErrorIndex;
                uiRes = NetUseAdd(null, 2, ref useinfo, out paramErrorIndex);
                IsConnected = uiRes == 0;
            }
            catch (Exception ex)
            {
                _logger.Error("UncHelper has crashed: ", ex);
                uiRes = 1;
                IsConnected = false;
            }
            return uiRes;
        }
    
        /// <summary>
        /// Delete the UNC connection
        /// </summary>
        private int NetUseDelete()
        {
            int nRes;
            try
            {
                nRes = (int)NetUseDel(null, _uncPath, 2);
            }
            catch (Exception ex)
            {
                nRes = Marshal.GetLastWin32Error();
                _logger.Error($"UncHelper.NetUseDelete Error: {nRes} 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);
            }
        }
    
        protected 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);
        }
    }
    
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.