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.