C# サンプル集 |
Visual Basic 中学校 > C# サンプル集 > C# サンプル集目次 >
ドライブの種類を判断する
2021/5/9
パスからドライブの種類を判断する
string path = @"E:\test\abc.mp3";
string driveName = System.IO.Path.GetPathRoot(path);
var drive = new System.IO.DriveInfo(driveName);
switch (drive.DriveType)
{
case System.IO.DriveType.CDRom:
System.Diagnostics.Debug.WriteLine(driveName + "はCD/DVD/Blu-rayなどの光学ドライブです。");
break;
case System.IO.DriveType.Fixed:
System.Diagnostics.Debug.WriteLine(driveName + "はSSDやハードディスクなどの固定ディスクです。");
break;
case System.IO.DriveType.Network:
System.Diagnostics.Debug.WriteLine(driveName + "はネットワークドライブです。");
break;
case System.IO.DriveType.NoRootDirectory:
System.Diagnostics.Debug.WriteLine(driveName + "は何もマウントされていないドライブなどです。");
break;
case System.IO.DriveType.Ram:
System.Diagnostics. Debug.WriteLine(driveName + "はRAMディスクです。");
break;
case System.IO.DriveType.Removable:
System.Diagnostics.Debug.WriteLine(driveName + "はUSBメモリーやSDカード、フロッピーディスクなどのリムーバブルドライブです。");
break;
case System.IO.DriveType.Unknown:
System.Diagnostics.Debug.WriteLine(driveName + "のドライブの種類は不明です。");
break;
}
メモ:調べるパスが実在している必要はありません。 存在しないドライブを指定すると NoRootDirectory と判断されます。
ドライブの一覧とその種類を列挙する
foreach (string driveName in System.IO.Directory.GetLogicalDrives())
{
var drive = new System.IO.DriveInfo(driveName);
System.Diagnostics.Debug.WriteLine($"{driveName} = {drive.DriveType}");
}
メモ:出力されるドライブの種類 Fixed や Removable などの意味は、上述の例を参照。
Windowsでの実行結果の例
C:\ = Fixed
D:\ = Fixed
E:\ = Removable
F:\ = Removable
Linux(Debian)での実行結果の例(抜粋)
/sys = Ram
/proc = Ram
/dev = Ram
/dev/pts = Ram
/run = Ram
/ = Fixed
/sys/kernel/security = Ram
/dev/shm = Ram
参考
DriveType 列挙型 (System.IO) | Microsoft Docs
GetDriveTypeA function (fileapi.h) - Win32 apps | Microsoft Docs