GooliveR
GooliveR

Reputation: 244

Copying files with limitation of 100MB

Help to finalize the make up of all files and folders, and copy them to a folder, you need to do to limit the folder to 100MB

How to make a constant check of the folders on the volume 100MB, if the limit of files in a folder is exceeded, to complete the copying.

public static void GetFilesList()
{
    long DS = 1000000;
    string[] extens = 
    { 
    ".txt", ".doc", 
    ".cs", ".ico", 
    ".Dll", ".Html", 
    ".Htm", ".Xml", 
    ".Php", ".png", 
    ".jpg", ".gif" 
    };
    if (DirSize(new DirectoryInfo(Easy.GooVer), DS) > DS)
    {
        foreach (string fileName in Directory.GetFiles(Easy.GooVer, "*.*", SearchOption.AllDirectories))
        {
            string ext = Path.GetExtension(fileName);
            if (Array.IndexOf(extens, ext) >= 0)
            { try{
              File.Copy(fileName, Path.Combine(Easy.str1, Path.GetFileName(fileName)), true);}catch { }
            }
        }
    }
}
public static long DirSize(DirectoryInfo d, long aLimit = 0)
{
    long Size = 0;
    FileInfo[] fis = d.GetFiles();
    foreach (FileInfo fi in fis)
    {
        Size += fi.Length;
        if (aLimit > 0 && Size > aLimit)
            return Size;
    }
    DirectoryInfo[] dis = d.GetDirectories();
    foreach (DirectoryInfo di in dis)
    {
        Size += DirSize(di, aLimit);
        if (aLimit > 0 && Size > aLimit)
            return Size;
    }
    return (Size);
}

P.S: I'm using .Net 2.0 and I don't want to use Linq.

Upvotes: 3

Views: 227

Answers (1)

L.B
L.B

Reputation: 116108

Your recursive code is not correct.

You can use a simpler code to get the directory size

public static long DirSize(DirectoryInfo d)
{
    return d.GetFiles("*.*", SearchOption.AllDirectories).Sum(f => f.Length);
}

Upvotes: 1

Related Questions