UNCなパス指定でネットワーク越しのファイルアクセスを認証からC#のプログラムからやりたい場合。 ドライブを登録するとか、あらかじめ、プログラム動かす端末から手でつないでおくといけるとかあるけども、プログラム側からちゃんと通しておきたい場合。とりあえず、C#の標準機能?としてはそういったものは無いらしい。WinAPIを呼んでやるしかない様子。↓ソース。どこかのサイトに載ってたやつほぼそのままだったと思うだけど、どこだったか覚えていない。。。
using System.Runtime.InteropServices; class Hoge { //接続まわり [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); //APIに渡す接続情報 [StructLayout(LayoutKind.Sequential)] public struct NETRESOURCE { public int dwScope;//列挙の範囲 public int dwType;//リソースタイプ public int dwDisplayType;//表示オブジェクト public int dwUsage;//リソースの使用方法 [MarshalAs(UnmanagedType.LPWStr)] public string lpLocalName;//ローカルデバイス名。使わないならNULL。 [MarshalAs(UnmanagedType.LPWStr)] public string lpRemoteName;//リモートネットワーク名。使わないならNULL [MarshalAs(UnmanagedType.LPWStr)] public string lpComment;//ネットワーク内の提供者に提供された文字列 [MarshalAs(UnmanagedType.LPWStr)] public string lpProvider;//リソースを所有しているプロバイダ名 } public string ServerUNC { get; set; } public string ServerId { get; set; } public string ServerPass { get; set; } public void ConnectServer() { //接続情報 ServerUNC = @"\\192.168.1.1\x$";//←ドライブ指定でもいける ServerId = "HimitsuNoId";//試してないけど"hoge\fugaid"みたいなドメイン付きも行けるとおもう。 ServerPass = "HimitsuNoPass"; NETRESOURCE netResource = new NETRESOURCE(); netResource.dwScope = 0; netResource.dwType = 1; netResource.dwDisplayType = 0; netResource.dwUsage = 0; netResource.lpLocalName = ""; netResource.lpRemoteName = ServerUNC; netResource.lpProvider = ""; int ret = 0; try { //既に接続がある場合は一回接続削除 ret = WNetCancelConnection2(ServerUNC, 0, true); //UNC名で接続 ret = WNetAddConnection2(ref netResource, ServerPass, ServerId, 0); } catch { //何かダメ } //↑が通れば後は普通にアクセス出来る DirectoryInfo di = new DirectoryInfo(Path.Combine(ServerUNC,@"hoge\fuga")); foreach(FileInfo tmp in di.GetFiles()) { Console.WriteLine(tmp.FullName); } } }
UNCの指定はエクスプローラで使えるならホスト名でも基本的に問題はないはず。ただ、名前解決が異常に遅いとか色々問題が出ることが多いので、個人的にはIPでやってる。正直、サーバのIP変わることなんて現実的に皆無なので。っていうか今まであったことがない。その前にリース切れるか更改するでしょ。
2016/07/01追記
プログラムを動かすユーザーによってうまくいかない事もある。特にWebアプリでやる場合、アプリケーションプールのIDがデフォルトのままだとほぼ確実にうまくいかない。IISで該当のアプリケーションプールをAdmin権限のユーザにするか、セキュリティ的にNGならアプリケーションプール用のユーザーをちゃんと作ってやらないとつなげない。