fc2ブログ

C#で共有フォルダへのアクセス

ユーザ名、パスワードを入力して、共有フォルダへアクセスし、
ファイルを操作する必要がありましたので、調べてみました。

参考にしたサイトは、以下です。
3流プログラマのメモ書き

とりあえず使うものは、
WNetAddConnection2      ← 接続用
WNetCancelConnection2  ← 切断用
というものらしいです。
詳しくは、参考にしたリンクを参考ください。

そのままメモしても意味が無いので、作成したクラスを載せておきます(--;)oO(ほぼコピペだけど)

作成したクラスは、IDisposableを実装し、オブジェクトが破棄されたときは、
削除されるようにしています。





using System;
using System.Runtime.InteropServices;

namespace myclass{
public class ConnectSharedFolder : IDisposable{

//接続切断するWin32 API を宣言
[DllImport("mpr.dll", EntryPoint ="WNetCancelConnection2",CharSet=
System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int WNetCancelConnection2(string lpName, Int32 dwFlags, bool fForce);

[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);

[StructLayout(LayoutKind.Sequential)]
internal 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;

}

#region MemberField
private string _path = "";
private string _usr = "";
private string _psw = "";
private bool _isConnect = false;
#endregion

public ConnectSharedFolder(string path, string username, string password) {
_path = path;
_usr = username;
_psw = password;
}

///
/// 共有フォルダへの接続
/// 共有フォルダパス
/// ユーザ名
/// パスワード
///
public int Connect() {
NETRESOURCE netResource = new NETRESOURCE();
netResource.dwScope = 0;
netResource.dwType = 1;
netResource.dwDisplayType = 0;
netResource.dwUsage = 0;
netResource.lpLocalName = "";
netResource.lpRemoteName = _path;
netResource.lpProvider = "";

int ret = 0;
try {
ret = WNetCancelConnection2(_path, 0, true);
ret = WNetAddConnection2(ref netResource, _psw, _usr, 0);
} catch (Exception exp) {
return -1;
}

_isConnect = true;
return ret;
}


///
/// 共有フォルダの切断
///
///
public int DisConnect() {
if (_isConnect)
return WNetCancelConnection2(_path, 0, false);
else
return 0;
}

public void Dispose() {
try {
if (_isConnect)
WNetCancelConnection2(_path, 0, false);
} catch {

}
}
}
}




コンストラクタで、必要なパラメータを取得し、
Connect()で接続、DisConnect()で切断です。

終わり。






スポンサーサイト



テーマ : プログラミング
ジャンル : コンピュータ

コメントの投稿

非公開コメント

プロフィール

ss_9

名前 :ss_9
紹介 :
20代はエンジニア、30代はプロ、40代は管理、50代は人脈。

Twitterボタン

最新記事
カテゴリ
AD
月別アーカイブ
RSSリンクの表示
RSSリンクの表示