แล้วก็มาถึง EP สุดท้ายของซีรีส์นี้ นั่นก็คือการดึงข้อมูลการใช้งานพื้นที่บน Disk
ก่อนจะไปหาพื้นที่ disk เราต้องไปหา drive กันก่อนว่ามี drive อะไรบ้าง จากนั้นจึงไปหาข้อมูล disk ของ drive นั้นๆ โดยเราจะใช้ class DriveInfo สำหรับดึงข้อมูล drive ต่างๆ ออกมา ดังโค้ดตัวอย่าง

โดยเราสามารถดึงข้อมูล drive ต่างๆ ได้ผ่านเมทธอด GetDrives() และเข้าถึงชื่อ drive ได้ผ่าน property Name
เมื่อมาถึงขั้นตอนนี้ เราก็สามารถเข้าถึงข้อมูลพื้นที่ disk และการใช้งานของแต่ละ drive ได้ไม่ยากแล้ว ผ่าน property ต่างๆ ของ object DriveInfo เราไปดูตัวอย่างโค้ดกันเลย

จากตัวอย่าง เราต้องตรวจสอบเพิ่มเติมว่า Drive ที่เราต้องการอยู่ในสถานะพร้อมใช้งานอยู่หรือไม่ผ่าน IsReady ก่อนที่จะเรียกใช้งานเมทธอดอื่น
เพื่อให้การแสดงผลข้อมูลอยู่ในรูปแบบที่เข้าใจง่าย และแปลงรูปแบบข้อมูลให้เป็น GB ก็จะได้ตัวอย่างโค้ดทั้งหมดดังต่อไปนี้
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
long B2GB = 1024 * 1024 * 1024;
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
if (drive.IsReady)
{
Console.WriteLine("Drive : " + drive.Name);
Console.WriteLine("Total Size : " + (drive.TotalSize / B2GB ).ToString("0.00") + " GB" );
Console.WriteLine("Available Free Space : " + (drive.AvailableFreeSpace / B2GB).ToString("0.00") + " GB");
}
}
}
}
}
ผลลัพธ์จากการรันโค้ดข้างต้น

นอกจากนี้ DriveInfo ยังมีอีกหลาย property ที่เราสามารถเรียกใช้งานได้ ดังตัวอย่าง
DriveInfo Properties | |
AvailableFreeSpace | Indicates the amount of available free space on a drive, in bytes. |
DriveFormat | Gets the name of the file system, such as NTFS or FAT32. |
DriveType | Gets the drive type, such as CD-ROM, removable, network, or fixed. |
IsReady | Gets a value that indicates whether a drive is ready. |
Name | Gets the name of a drive, such as C:. |
RootDirectory | Gets the root directory of a drive. |
TotalFreeSpace | Gets the total amount of free space available on a drive, in bytes. |
TotalSize | Gets the total size of storage space on a drive, in bytes. |
VolumeLabel | Gets or sets the volume label of a drive. |
สำหรับบทความในซีรี่ส์นี้ก็ขอจบแต่เพียงเท่านี้ หวังว่าจะมีประโยชน์บ้างไม่มากก็น้อย พบกันใหม่เมื่อมีเรื่องอยากจะเขียน
สวัสดีครับ
อ้างอิง