0

i am trying to get the available disk space of a CD or a DVD using DiskInfo object functions but never succeeded. I understood that CDROM is a read only file system that every bit on it would be considered as allocated thus when anyone tries to get the available space on disk using normal functions will fail. I also tried to use wmic api but also failed.

And here is My code:

foreach (var drive in DriveInfo.GetDrives())
{
    double freeSpace = drive.TotalFreeSpace;
    double totalSpace = drive.TotalSize;
    double percentFree = (freeSpace / totalSpace) * 100;
    float num = (float)percentFree;

    Console.WriteLine("Drive:{0} With {1} % free", drive.Name, num);
    Console.WriteLine("Space Remaining:{0}", drive.AvailableFreeSpace);
    Console.WriteLine("Percent Free Space:{0}", percentFree);
    Console.WriteLine("Space used:{0}", drive.TotalSize);
    Console.WriteLine("Type: {0}", drive.DriveType);
}

below is a sample of what could any c# code i tried would return.

letter :C - total :244095 - free :75851 - type: Fixed
letter :E - total :NULL- free :NULL- type: CDRom

After @kettch and @Craig Selbert reply below i tried another way using GetDiskFreeSpaceEx function but it dose not work probably, and here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;

namespace IMAPIv2
{
    public class Burn
    {
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
        out ulong lpFreeBytesAvailable,
        out ulong lpTotalNumberOfBytes,
        out ulong lpTotalNumberOfFreeBytes);


        ImageMaster _imageMaster;

        public String burnData(String filesToBurn,String driverIndex,String volumeLabel,String boolColseMedia,String boolEject){
            try
            {

                String[] sep = { "<!>" };
                String[] files = filesToBurn.Split(sep, StringSplitOptions.RemoveEmptyEntries);
                DriveInfo driver = getSelectedDriver(int.Parse(driverIndex));
                Console.WriteLine(driver.Name);
                Console.WriteLine(getDirSize(driver.Name));

                ulong FreeBytesAvailable;
                ulong TotalNumberOfBytes;
                ulong TotalNumberOfFreeBytes;

                bool success = GetDiskFreeSpaceEx(driver.Name, out FreeBytesAvailable, out TotalNumberOfBytes,
                                   out TotalNumberOfFreeBytes);
                if (!success)
                    throw new System.ComponentModel.Win32Exception();

                Console.WriteLine("Free Bytes Available:      {0,15:D}", FreeBytesAvailable);
                Console.WriteLine("Total Number Of Bytes:     {0,15:D}", TotalNumberOfBytes);
                Console.WriteLine("Total Number Of FreeBytes: {0,15:D}", TotalNumberOfFreeBytes);

                _imageMaster = new ImageMaster();
                _imageMaster._recorders.SelectedIndex = Convert.ToInt32(driverIndex);
                _imageMaster.LoadRecorder();
                _imageMaster.totalFilesToBurn = addFilesToBurn(files);
                _imageMaster.VolumeLabel = volumeLabel;
                _imageMaster.LoadMedia();
                _imageMaster.WriteImage(BurnVerificationLevel.Quick, Convert.ToBoolean(boolColseMedia), Convert.ToBoolean(boolEject));
            }
            catch (Exception e)
            {
                throw e;
            }
            String[] res = { "P:Finished" };
            return res[0];
    }

    private long addFilesToBurn(String[] files)
    {
        long totalSize = 0;
        for (int i = 0; i < files.Length; i++)
        {
            FileAttributes attr = File.GetAttributes(files[i]);
            if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
            {
                _imageMaster.Nodes.Add(new DirectoryNode(files[i]));
            }
            else
            {
                _imageMaster.Nodes.Add(new FileNode(files[i]));
                totalSize += new FileNode(files[i]).SizeOnDisc;
            }
        }
        return totalSize;

    }

    private DriveInfo getSelectedDriver(int driverindex)
    {
        DriveInfo[] df = DriveInfo.GetDrives();
        DriveInfo selectedDriver = null;
        int index  = 0;
        foreach ( DriveInfo d in df){
            if (d.DriveType.Equals(DriveType.CDRom)){
                if(index == driverindex){
                    selectedDriver= d;
                    break;
                }
                index++;
            }
        }

        if (selectedDriver == null){
            if (index == 0)
            {
                throw new InvalidOperationException("Please make sure you have a working optical drive to continue");
            }
            else
            {
                foreach (DriveInfo d in df)
                {
                    if (d.DriveType.Equals(DriveType.CDRom))
                    {
                       selectedDriver = d;
                       break;
                    }
                }
            }
        }

        return selectedDriver;


    }

    private long getDirSize(String dir)
    {
        long s = 0;
        DirectoryInfo df = new DirectoryInfo(dir);
        foreach (FileInfo f in df.GetFiles())
        {
            s += f.Length;
        }

        foreach (DirectoryInfo d in df.GetDirectories())
        {
            s += getDirSize(d.FullName);
        }

        return s;
    }






    }
}

The output for this code is:

E:\
296589891
Free Bytes Available:                    0
Total Number Of Bytes:              309248
Total Number Of Free Bytes:               0

The free disk space is always returned as zero, however it is not as shown in the image

Here

Any help would be appreciated, thanks in advance.

Mohammad Fneish
  • 829
  • 1
  • 9
  • 20

0 Answers0