كيفية اكتشاف أجهزة تخزين USB ومحركات الأقراص المضغوطة/أقراص DVD القابلة للكتابة (C#)
سؤال
كيف يمكنني اكتشاف أي أجهزة تخزين USB و/أو ناسخة أقراص مضغوطة/أقراص DVD متوفرة في وقت معين (باستخدام C# .Net2.0).
أود أن أقدم للمستخدمين إمكانية اختيار الأجهزة التي يمكن تخزين الملف عليها لإزالتها فعليًا - على سبيل المثال.وليس القرص الصلب.
المحلول
using System.IO;
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
if (d.IsReady && d.DriveType == DriveType.Removable)
{
// This is the drive you want...
}
}
وثائق فئة DriveInfo موجودة هنا:
http://msdn.microsoft.com/en-us/library/system.io.driveinfo.aspx
نصائح أخرى
هذا هو رمز VB.NET للتحقق من وجود أي محركات أقراص قابلة للإزالة أو محركات أقراص CDRom متصلة بالكمبيوتر:
Me.lstDrives.Items.Clear()
For Each item As DriveInfo In My.Computer.FileSystem.Drives
If item.DriveType = DriveType.Removable Or item.DriveType = DriveType.CDRom Then
Me.lstDrives.Items.Add(item.Name)
End If
Next
لن يكون من الصعب تعديل هذا الرمز إلى ما يعادله في c#، وأكثر من ذلك نوع القيادةمتاحة.
من MSDN:
- مجهول: نوع محرك الأقراص غير معروف.
- NoRootDirectory: لا يحتوي محرك الأقراص على دليل جذر.
- قابل للإزالة: محرك الأقراص هو جهاز تخزين قابل للإزالة، مثل محرك الأقراص المرنة أو محرك أقراص USB المحمول.
- مُثَبَّت: محرك الأقراص هو قرص ثابت.
- شبكة: محرك الأقراص هو محرك أقراص الشبكة.
- قرص مدمج: محرك الأقراص عبارة عن جهاز قرص ضوئي، مثل القرص المضغوط أو قرص DVD-ROM.
- كبش: محرك الأقراص هو قرص RAM.
في c# يمكنك الحصول على نفس الشيء باستخدام فئة System.IO.DriveInfo
using System.IO;
public static class GetDrives
{
public static IEnumerable<DriveInfo> GetCDDVDAndRemovableDevices()
{
return DriveInfo.GetDrives().
Where(d => d.DriveType == DriveType.Removable
&& d.DriveType == DriveType.CDRom);
}
}
هذه وحدة كاملة لـ VB.NET:
نظام الواردات.IO
الوحدة النمطية GetDriveNamesByType
الدالة GetDriveNames (اختياري ByVal DType كـ DriveType = DriveType.Removable) كـ ListBox
لكل DN مثل System.IO.DriveInfo في My.Computer.FileSystem.Drives
إذا DN.DriveType = DType ثم
GetDriveNames.Items.Add(DN.Name)
إنهاء إذا
التالي
وظيفة النهاية
وحدة النهاية
'Drive Types <br>
'Unknown: The type of drive is unknown. <br>
'NoRootDirectory: The drive does not have a root directory. <br>
'Removable: The drive is a removable storage device, such as a floppy disk drive or a USB flash drive. <br>
'Fixed: The drive is a fixed disk. <br>
'Network: The drive is a network drive. <br>
'CDRom: The drive is an optical disc device, such as a CD or DVD-ROM. <br>
'Ram: The drive is a RAM disk. <br>