Follow in Twitter & Facebook

Like in Facebook

Powered By Blogger Widgets

Free Download

FREE Tools

Thursday, October 11, 2012

Get drive info in C#.Net Part-2

In Part-1 we have discussed how to get driver information using C#.Net. In this article we will get some more driver information like Total size of the drive and free space in the drive.

Previously I have also explained about PowerShell, SharePoint 2013 article as well as Session state in Asp.Net and Exception class in Asp.Net.

We can use the same System.IO namespace to work with files, directory and drives. Below is the code to retrieve the information.

HTML Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="IOSamples.aspx.cs" Inherits="IOSamples" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
        <asp:Label ID="lblDrivers" runat="server" Text=""></asp:Label>

.cs Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class IOSamples : System.Web.UI.Page
    string drivers = "";
    protected void Page_Load(object sender, EventArgs e)
        string allDrivers = GetDriverInfo();
        lblDrivers.Text = allDrivers;

    string GetDriverInfo()
        foreach (var drive in DriveInfo.GetDrives())
            if (drive.IsReady)
                drivers += "Driver Name: " + drive.Name + "<br/>" + " Drive Type: " + drive.DriveType + "<br/>" + " Total Size " + GetSize(drive.TotalSize) + "<br/>" + " Total Free Space " + GetSize(drive.TotalFreeSpace) + "<br/>";
                drivers = "The driver is not ready !";
        return drivers;

    static string GetSize(double size)
        var prefixes = new[] { "bytes", "KB", "MB", "GB", "TB", "PB", "EB" };
        int i;
        for (i = 0; size > 1000; i++)
            size /= 1024;
        return string.Format("{0:##0.##} {1}", size, prefixes[i]);

The out put is shown as in the figure below:

0 on: "Get drive info in C#.Net Part-2"