NetworkShareUtility.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace LAPS_XMLQC_Service.App_Data
  4. {
  5. public class NetworkShareUtility
  6. {
  7. [DllImport("mpr.dll")]
  8. private static extern int WNetAddConnection2(ref NETRESOURCE netResource,
  9. string password, string username, int flags);
  10. [DllImport("mpr.dll")]
  11. private static extern int WNetCancelConnection2(string name, int flags, bool force);
  12. [StructLayout(LayoutKind.Sequential)]
  13. private struct NETRESOURCE
  14. {
  15. public int dwScope;
  16. public int dwType;
  17. public int dwDisplayType;
  18. public int dwUsage;
  19. public string lpLocalName;
  20. public string lpRemoteName;
  21. public string lpComment;
  22. public string lpProvider;
  23. }
  24. public static void ConnectToShare(string uncPath, string username, string password)
  25. {
  26. var netResource = new NETRESOURCE
  27. {
  28. dwType = 1, // RESOURCETYPE_DISK
  29. lpRemoteName = uncPath
  30. };
  31. // flags=0 → create connection
  32. int result = WNetAddConnection2(ref netResource, password, username, 0);
  33. if (result != 0 && result != 1219) // 1219 = already connected
  34. {
  35. throw new Exception($"Error connecting to remote share. Error code: {result}");
  36. }
  37. }
  38. public static void DisconnectFromShare(string uncPath)
  39. {
  40. WNetCancelConnection2(uncPath, 0, true);
  41. }
  42. }
  43. }