Find a Drive With Max Space and Write Permissions c#, (.Net) Dot Net

Code Snippets 4 U
 static void Main(string[] args)
        {
            DriveInfo[] driveInfo = DriveInfo.GetDrives();
            string osDrive = Path.GetPathRoot(Environment.SystemDirectory);

            // now try to find the directory which have max space and have write permission
            // find the drive having max space
            var maxSpace = driveInfo.Max(item => { try { return item.TotalFreeSpace; } catch (Exception) { return 0; } });
            var driveWithMaxSpace = driveInfo.FirstOrDefault(item => item.TotalFreeSpace == maxSpace && Directory.Exists(item.Name));

            // return empty string if driveWithMaxSpace is null
            if (driveWithMaxSpace == null) throw new NoDriveFoundException("Your Message");

            // check if the drive is os drive
            if (driveWithMaxSpace.Name == osDrive)
            {
                // return the public directory documents path
                return osDrive + @"Users\Public\Downloads";
            }
            else
            {
                // return the drive as it is
                return driveWithMaxSpace.Name;
            }
        }

Exception Code is Below:

class NoDriveFoundException : Exception
    {
        public NoDriveFoundException(string msg) : base(msg) { }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

− three = 2