2015年4月16日 星期四

[C#] 取得電腦上所有磁碟代號

程式碼
 using System;  
 using System.Collections.Generic;  
 using System.ComponentModel;  
 using System.Data;  
 using System.Drawing;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 using System.Windows.Forms;  
 namespace Dispaly_all_logic_driver  
 {  
   public partial class Form1 : Form  
   {  
     public Form1()  
     {  
       InitializeComponent();  
       //把裝置代碼加入ListBox裡  
       List<string> list = get_all_logic_driver();  
       foreach (string drive in list)  
         listBox1.Items.Add(drive);  
     }  
     /// <summary>  
     /// 取得電腦上所有邏輯裝置代碼  
     /// </summary>  
     /// <returns></returns>  
     private List<string> get_all_logic_driver()  
     {  
       List<string> list = new List<string>();  
       foreach (string drive in Environment.GetLogicalDrives())  
       {  
         list.Add(drive);  
       }  
       return list;  
     }  
   }  
 }  


執行畫面如下













如果要識別出那個是光碟機需要呼叫WINDOWS API 來判斷DviveType

  [DllImport("kernel32", SetLastError = true)]  
     public static extern int GetDriveType(string driveLetter);  

完整程式如下

 using System;  
 using System.Collections.Generic;  
 using System.ComponentModel;  
 using System.Data;  
 using System.Drawing;  
 using System.Linq;  
 using System.Runtime.InteropServices;  
 using System.Text;  
 using System.Threading.Tasks;  
 using System.Windows.Forms;  
 namespace Dispaly_all_logic_driver  
 {  
   public partial class Form1 : Form  
   {  
     [DllImport("kernel32", SetLastError = true)]  
     public static extern int GetDriveType(string driveLetter);  
     public Form1()  
     {  
       InitializeComponent();  
       //把裝置代碼加入ListBox裡  
       List<string> list = get_all_logic_driver();  
       foreach (string drive in list)  
         listBox1.Items.Add(drive);  
     }  
     /// <summary>  
     /// 取得電腦上所有邏輯裝置代碼  
     /// </summary>  
     /// <returns></returns>  
     private List<string> get_all_logic_driver()  
     {  
       List<string> list = new List<string>();  
       foreach (string drive in Environment.GetLogicalDrives())  
       {  
         if (GetDriveType(drive) == 5)  //CDROM type  
           list.Add(drive);  
       }  
       return list;  
     }  
   }  
 }  

執行結果













我的裝置




type代碼

ValueConstantMeaning
1SYSTEM_WINDRIVE_ERRORNon-existent drive or other error
2SYSTEM_WINDRIVE_REMOVABLERemovable drive (e.g. floppy)
3SYSTEM_WINDRIVE_FIXEDHarddisk
4SYSTEM_WINDRIVE_REMOTENetwork share
5SYSTEM_WINDRIVE_CDROMCD-Rom or DVD
6SYSTEM_WINDRIVE_RAMDISKRAM disk

參考資料請參考這一篇
https://pear.php.net/manual/fr/package.system.windrives.windrives.getdrivetype.php


沒有留言:

張貼留言