{"id":3164,"date":"2020-01-21T10:15:24","date_gmt":"2020-01-21T09:15:24","guid":{"rendered":"https:\/\/solidt.eu\/site\/?p=3164"},"modified":"2022-07-25T08:33:24","modified_gmt":"2022-07-25T07:33:24","slug":"c-access-a-untrusted-network-share","status":"publish","type":"post","link":"https:\/\/solidt.eu\/site\/c-access-a-untrusted-network-share\/","title":{"rendered":"C# Access a (untrusted) network share"},"content":{"rendered":"\n<p>Source: <a href=\"https:\/\/stackoverflow.com\/a\/14870774\">https:\/\/stackoverflow.com\/a\/14870774<\/a><\/p>\n\n\n\n<p><strong>Note: <\/strong><br> The share path must NOT end with a \\ (backslash)<br> or it will result in the exception: <strong>The network path was not found<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public static class NetworkShareConsts\n{\n\tpublic const int RESOURCE_CONNECTED = 0x00000001;\n\tpublic const int RESOURCE_GLOBALNET = 0x00000002;\n\tpublic const int RESOURCE_REMEMBERED = 0x00000003;\n\n\tpublic const int RESOURCETYPE_ANY = 0x00000000;\n\tpublic const int RESOURCETYPE_DISK = 0x00000001;\n\tpublic const int RESOURCETYPE_PRINT = 0x00000002;\n\n\tpublic const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;\n\tpublic const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;\n\tpublic const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002;\n\tpublic const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003;\n\tpublic const int RESOURCEDISPLAYTYPE_FILE = 0x00000004;\n\tpublic const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005;\n\n\tpublic const int RESOURCEUSAGE_CONNECTABLE = 0x00000001;\n\tpublic const int RESOURCEUSAGE_CONTAINER = 0x00000002;\n\n\tpublic const int CONNECT_INTERACTIVE = 0x00000008;\n\tpublic const int CONNECT_PROMPT = 0x00000010;\n\tpublic const int CONNECT_REDIRECT = 0x00000080;\n\tpublic const int CONNECT_UPDATE_PROFILE = 0x00000001;\n\tpublic const int CONNECT_COMMANDLINE = 0x00000800;\n\tpublic const int CONNECT_CMD_SAVECRED = 0x00001000;\n\n\tpublic const int CONNECT_LOCALDRIVE = 0x00000100;\n\n\t\/\/\/ Errors\n\tpublic const int NO_ERROR = 0;\n\n\tpublic const int ERROR_ACCESS_DENIED = 5;\n\tpublic const int ERROR_ALREADY_ASSIGNED = 85;\n\tpublic const int ERROR_BAD_DEVICE = 1200;\n\tpublic const int ERROR_BAD_NET_NAME = 67;\n\tpublic const int ERROR_BAD_PROVIDER = 1204;\n\tpublic const int ERROR_CANCELLED = 1223;\n\tpublic const int ERROR_EXTENDED_ERROR = 1208;\n\tpublic const int ERROR_INVALID_ADDRESS = 487;\n\tpublic const int ERROR_INVALID_PARAMETER = 87;\n\tpublic const int ERROR_INVALID_PASSWORD = 1216;\n\tpublic const int ERROR_MORE_DATA = 234;\n\tpublic const int ERROR_NO_MORE_ITEMS = 259;\n\tpublic const int ERROR_NO_NET_OR_BAD_PATH = 1203;\n\tpublic const int ERROR_NO_NETWORK = 1222;\n\n\tpublic const int ERROR_BAD_PROFILE = 1206;\n\tpublic const int ERROR_CANNOT_OPEN_PROFILE = 1205;\n\tpublic const int ERROR_DEVICE_IN_USE = 2404;\n\tpublic const int ERROR_NOT_CONNECTED = 2250;\n\tpublic const int ERROR_OPEN_FILES = 2401;\n}<\/pre>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public class NetworkShareConnection : IDisposable\n{\n\tpublic string UncPath { get; private set; }\n\tpublic string UserName { get; private set; }\n\tpublic string Password { get; private set; }\n\n\t#region PInvoke Signatures\n\t[DllImport(\"Mpr.dll\")]\n\tprivate static extern int WNetUseConnection(IntPtr hwndOwner, NETRESOURCE lpNetResource,\n\t\tstring lpPassword, string lpUserID, int dwFlags, string lpAccessName, string lpBufferSize, string lpResult);\n\n\t[DllImport(\"Mpr.dll\")]\n\tprivate static extern int WNetCancelConnection2(string lpName, int dwFlags, bool fForce);\n\n\t[StructLayout(LayoutKind.Sequential)]\n\tprivate class NETRESOURCE\n\t{\n\t\tpublic int dwScope = 0;\n\t\tpublic int dwType = 0;\n\t\tpublic int dwDisplayType = 0;\n\t\tpublic int dwUsage = 0;\n\t\tpublic string lpLocalName = \"\";\n\t\tpublic string lpRemoteName = \"\";\n\t\tpublic string lpComment = \"\";\n\t\tpublic string lpProvider = \"\";\n\t}\n\t#endregion\n\n\tpublic NetworkShareConnection(string uncPath, string userName, string password)\n\t{\n\t\tUncPath = uncPath;\n\t\tUserName = userName;\n\t\tPassword = password;\n\t\tConnectToShare(UncPath, UserName, Password, false);\n\t}\n\n\tprivate void ConnectToShare(string remoteUnc, string username, string password, bool promptUser)\n\t{\n\t\tNETRESOURCE nr = new NETRESOURCE { dwType = NetworkShareConsts.RESOURCETYPE_DISK, lpRemoteName = remoteUnc };\n\t\tint result;\n\t\tif (promptUser)\n\t\t{\n\t\t\tresult = WNetUseConnection(IntPtr.Zero, nr, \"\", \"\", NetworkShareConsts.CONNECT_INTERACTIVE | NetworkShareConsts.CONNECT_PROMPT, null, null, null);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tresult = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);\n\t\t}\n\t\tif (result != NetworkShareConsts.NO_ERROR)\n\t\t{\n\t\t\tthrow new Win32Exception(result);\n\t\t}\n\t}\n\n\tprivate void DisconnectFromShare(string remoteUnc)\n\t{\n\t\tint result = WNetCancelConnection2(remoteUnc, NetworkShareConsts.CONNECT_UPDATE_PROFILE, false);\n\t\tif (result != NetworkShareConsts.NO_ERROR)\n\t\t{\n\t\t\tthrow new Win32Exception(result);\n\t\t}\n\t}\n\n\tpublic void Dispose()\n\t{\n\t\tDisconnectFromShare(UncPath);\n\t}\n}<\/pre>\n\n\n\n<p>Example:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">public string GetNetworkShare(string networkPath)\n{\n\tvar regEx = new Regex(@\"(\\\\\\\\.*?\\\\[^\\\\]*)\");\n\treturn regEx.Match(networkPath)?.Groups[0]?.Value;\n}\nvar networkPath = @\"\\\\192.168.0.10\\C$\\test\";\nvar filePath = Path.Combine(networkPath, fileName);\nusing (new NetworkShareConnection(GetNetworkShare(networkPath), userName, password))\n{\n        if (!Directory.Exists(networkPath))\n                Directory.CreateDirectory(networkPath);\n\tusing (var fs = File.OpenWrite(filePath))\n\t{\n\t\tdata.CopyTo(fs);\n\t}\n}<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Source: https:\/\/stackoverflow.com\/a\/14870774 Note: The share path must NOT end with a \\ (backslash) or it will result in the exception: The network path was not found Example:<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[6,4,1],"tags":[],"class_list":["post-3164","post","type-post","status-publish","format-standard","hentry","category-dotnet","category-programming","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/3164","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/comments?post=3164"}],"version-history":[{"count":8,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/3164\/revisions"}],"predecessor-version":[{"id":3256,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/posts\/3164\/revisions\/3256"}],"wp:attachment":[{"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/media?parent=3164"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/categories?post=3164"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/solidt.eu\/site\/wp-json\/wp\/v2\/tags?post=3164"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}