簡體   English   中英

循環時如何檢查目錄中所有文件的大小?

[英]How do i check for all the files sizes in a directory while in a loop?

s = Environment.GetEnvironmentVariable("UserProfile") + "\\Pictures";
            string[] photosfiles = Directory.GetFiles(t, "*.*", SearchOption.AllDirectories);
            for (int i = 0; i < s.Length; i++)
            {

                File.Copy(photosfiles[i], tempphotos + "\\" + Path.GetFileName(photosfiles[i]), true);

            }

這會將文件從一個目錄復制到另一個目錄。 我想一直檢查FOR循環內的目標目錄大小。 例如,首先復制一個文件以檢查文件大小(如果小於50mb繼續)。

復制第二個文件后,循環中的下一個迭代將檢查目標目錄大小中的兩個文件,如果兩個文件大小均小於50mb,則繼續。 依此類推,直到達到50mb,然后停止循環。

您可以在開始復制文件之前先計算目錄的大小,然后在復制文件時增加每個文件的大小,也可以在每次復制文件后重新計算目錄的大小。 我認為,后一種方法可能更准確,但效率也要低得多,具體取決於要復制的文件的大小(如果它們很小,則最終將它們計數很多次)。

要獲取目錄的大小,請使用:

public static long DirSize(DirectoryInfo d) 
{    
    long Size = 0;    
    // Add file sizes.
    FileInfo[] fis = d.GetFiles();
    foreach (FileInfo fi in fis) 
    {      
        Size += fi.Length;    
    }
    // Add subdirectory sizes.
    DirectoryInfo[] dis = d.GetDirectories();
    foreach (DirectoryInfo di in dis) 
    {
        Size += DirSize(di);   
    }
    return(Size);  
}

在此處用作示例的函數: http : //msdn.microsoft.com/zh-cn/library/system.io.directory(v=vs.100).aspx

因此您的代碼如下所示:

for (int i = 0; i < photosfiles.Length; i++)
{
    FileInfo fi(photosfiles[i]);

    DirectoryInfo d = new DirectoryInfo(tempphotos);
    long dirSize = DirSize(d);

    //if copying the file would take the directory over 50MB then don't do it
    if ((dirSize + fi.length) <= 52428800)
        fi.CopyTo(tempphotos + "\\" + fi.Name)
    else
        break;
}

您可以利用以下代碼:

string[] sizes = { "B", "KB", "MB", "GB" };
    double len = new FileInfo(filename).Length;
    int order = 0;
    while (len >= 1024 && order + 1 < sizes.Length) {
        order++;
        len = len/1024;
    }

    // Adjust the format string to your preferences. For example "{0:0.#}{1}" would
    // show a single decimal place, and no space.
    string result = String.Format("{0:0.##} {1}", len, sizes[order]);

要么

static String BytesToString(long byteCount)
{
    string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
    if (byteCount == 0)
        return "0" + suf[0];
    long bytes = Math.Abs(byteCount);
    int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
    double num = Math.Round(bytes / Math.Pow(1024, place), 1);
    return (Math.Sign(byteCount) * num).ToString() + suf[place];
}

這兩個答案都來自鏈接。 如何使用.NET獲得人類可讀的文件大小(以字節縮寫為單位)?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM