Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9723

C#で共有フォルダに接続する

$
0
0
接続機能クラス Connectで接続、DisConnectで切断。 WNetAddConnection2 と WNetCancelConnection2 の引数と戻り値は下記サイトが詳しい。 public class RemoteHostConnection { private NETRESOURCE netResource; [DllImport("mpr.dll", EntryPoint = "WNetAddConnection2", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] private static extern int WNetAddConnection2(ref NETRESOURCE lpNetResource, string lpPassword, string lpUsername, Int32 dwFlags); [DllImport("mpr.dll", EntryPoint = "WNetCancelConnection2", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] private static extern int WNetCancelConnection2(string lpName, Int32 dwFlags, bool fForce); private string RemoteHostIP { get; set; } private string RemoteHostUserID { get; set; } private string RemoteHostPassword { get; set; } /// <summary> /// コンストラクタ /// </summary> /// <param name="remoteHostIP">リモートコンピュータのIP。( 例:192.168.1.1 )</param> /// <param name="remoteHostUserID">ログインID ( 例:user )</param> /// <param name="remoteHostPassword">パスワード ( 例:password )</param> public RemoteHostConnection(string remoteHostIP, string remoteHostUserID, string remoteHostPassword) { RemoteHostIP = $@"\\{remoteHostIP}"; RemoteHostUserID = remoteHostUserID; RemoteHostPassword = remoteHostPassword; } [StructLayout(LayoutKind.Sequential)] public struct NETRESOURCE { public int dwScope; public int dwType; public int dwDisplayType; public int dwUsage; [MarshalAs(UnmanagedType.LPWStr)] public string lpLocalName; [MarshalAs(UnmanagedType.LPWStr)] public string lpRemoteName; [MarshalAs(UnmanagedType.LPWStr)] public string lpComment; [MarshalAs(UnmanagedType.LPWStr)] public string lpProvider; } //(戻り値 == 0)は成功。 0以外は失敗。 public int Connect() { netResource.dwScope = 0; netResource.dwType = 1; netResource.dwDisplayType = 0; netResource.dwUsage = 0; netResource.lpLocalName = null; netResource.lpRemoteName = RemoteHostIP; netResource.lpProvider = null; int ret = WNetCancelConnection2(RemoteHostIP, 0, true); ret = WNetAddConnection2(ref netResource, RemoteHostPassword, RemoteHostUserID, 0); return ret; } //(戻り値 == 0)は成功。 0以外は失敗。 public int DisConnect() { return WNetCancelConnection2(RemoteHostIP, 0, true); } } 使い方 var connection = new RemoteHostConnection("192.168.1.1","user","password"); if(connection.Connect() == 0) { //共有フォルダにファイルコピーしたり削除したりする。 connection.DisConnect(); }

Viewing all articles
Browse latest Browse all 9723

Trending Articles