ホームに戻る
出典 :
関連 :
目次 :
ネットワークドライブの割り当て
特定のディレクトリ(ネットワーク上のリソースに限らず、ローカル(自PC)のロケーションでも可)にドライブレターを割り当てる。
コマンド例 (PowerShell)
# ネットワークドライブを割り当てる
# (\\ComputerName\Users\Takaha-Q\sagawa を J: ドライブとする)
New-PSDrive -Persist -Name J -PSProvider FileSystem -Root \\ComputerName\Users\Takaha-Q\sagawa
# 割り当てられているドライブの一覧を表示する
Get-PSDrive
# ネットワークドライブの割り当てを解除する
# (J: ドライブを解放する)
Remove-PSDrive -Name J
実行権限とネットワークドライブとの関係
Windowsアプリケーションを管理者権限で実行している場合、アプリケーションからネットワークドライブに直接アクセスすることができない。
実行権限 |
実ドライブ(C:) へのアクセス |
ネットワークドライブ(J:) へのアクセス |
一般 |
可 |
可 |
管理者 |
可 |
不可 |
この問題への対処
ネットワークドライブのUNCパスを取得し、UNCパスに対してアクセスする。
クラス・関数定義
ライブラリ mpr.dll の WNetGetConnection() を用いる。
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
public static class MappedDriveResolver
{
// - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = -
// [static]UNCパスを取得する
// -------+---------------------------------------------------------------------
// 引数 | string path_Org : [I]変換前のパス
// -------+---------------------------------------------------------------------
// 戻り値 | string : 変換後のパス(UNC)
// -------+---------------------------------------------------------------------
// - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = - = -
[DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern int WNetGetConnection([MarshalAs(UnmanagedType.LPTStr)] string localName,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,
ref int length);
public static string GetUNCPath(string path_Org)
{
// path_Org がドライブレターを含む場合
// ("a:"~"z:" または "A:" ~ "Z:" で始まる)
char l = path_Org[0];
if ( (path_Org.Length > 2 ) &&
(path_Org[1] == ':' ) &&
( (l >= 'a' && l <= 'z') ||
(l >= 'A' && l <= 'Z') ) )
{
StringBuilder sb = new StringBuilder(512);
int size = sb.Capacity;
// 接続先のUNCパスを返す
WNetGetConnection(path_Org.Substring(0, 2), sb, ref size);
string path_Mod = Path.GetFullPath(path_Org).Substring(Path.GetPathRoot(path_Org).Length);
return Path.Combine(sb.ToString().TrimEnd(), path_Mod);
}
// 元のパスを返す
return path_Org;
}
} // public static class MappedDriveResolver
関数コール
// MappedDriveResolver クラスの GetUNCPath() メソッドをコール
// ネットワークドライブ下のロケーションを渡す
MappedDriveResolver.GetUNCPath(@"J:\ChildDir");
引数・戻り値の相関(例)
(\\ComputerName\AnyDir にドライブレター J: を割り当てている場合)
引数 |
戻り値 |
@"J:" |
@"J:" (変換失敗) |
@"J:\" |
@"\\ComputerName\AnyDir" |
@"J:\ChildDir" |
@"\\ComputerName\AnyDir\ChildDir" |
@"J:\ChildDir\" |
@"\\ComputerName\AnyDir\ChildDir\" |