Question

Is there a way using C# to get a folder size (used space on drive) located on a NAS or on a network shared directory I.e.: \\myNASdrive\MediaFiles?

I already tried something like this:

string[] a = Directory.GetFiles(p, "*.*");
long b = 0;
foreach (string name in a)
{       
    FileInfo info = new FileInfo(name);
    b += info.Length;
}   
return b;

But this works for local folders only.

Also we've tried using user impersonation but with no results.

Was it helpful?

Solution

Assuming you have the right permissions, this should do it;

using System;
using System.Runtime.InteropServices;

namespace DiskFreeSpaceEx
{
    internal class FreeSpace
    {
        [DllImport("kernel32")]
        public static extern int GetDiskFreeSpaceEx(string lpDirectoryName,ref long    lpFreeBytesAvailable,ref long lpTotalNumberOfBytes,ref long lpTotalNumberOfFreeBytes);
        const string RootPathName = @"\\server\share";
        private static void Main(string[] args)
        {
            long freeBytesAvailable = 0;
            long totalNumberOfBytes = 0;
            long totalNumberOfFreeBytes = 0;

            GetDiskFreeSpaceEx(RootPathName, ref freeBytesAvailable, ref
               totalNumberOfBytes, ref totalNumberOfFreeBytes);

            Console.WriteLine("{0}\t{1}\t{2}\t{3}", RootPathName,
                freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes);
        }
    }
}

Uses P/Invoke to get the information. Make sure you change the server and share.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top