2011-09-21 83 views
0

我正在嘗試編寫一個應用程序來使用以下代碼計算一組共享的大小。然而,問題在於,隨着搜索深入到共享中,循環中的文件路徑變量變得很大,引發異常並因此不能繼續。我發現一些說合並@"\\?\"允許charachter計數增加,但我不知道如何正確地追加它。正如您所期望的,我的份額採用\\server\name的形式。幫助文件夾路徑的大小

謝謝。

try 
{ 
    //Checks if the path is valid or not 
    if (!Directory.Exists(folder)) 
    { 
     return folderSize; 
    } 
    else 
    { 
     try 
     { 
      foreach (string filePath in Directory.GetFiles(folder)) 
      { 
       if (File.Exists(filePath)) 
       { 
        FileInfo finfo = new FileInfo(filePath); 
        folderSize += finfo.Length; 
       } 
      } 

      foreach (string dir in Directory.GetDirectories(folder)) 
       folderSize += GetDirectorySize(dir); 
     } 
     catch (NotSupportedException e) 
     { 
      Console.WriteLine("Unable to calculate folder size: {0}", e.Message); 
     } 
    } 
} 

例外試圖參考答案

'A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll 
'ShareSizes.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Configuration\2.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 
Could not find file 'Shortcut to fileName'. 
    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 
    at System.IO.FileInfo.get_Length() 
    at ShareSizes.Form1.button1_Click(Object sender, EventArgs e) in C:\Documents and Settings\...line 50 
+0

你是怎麼嘗試將您當前的路徑與這些字符結合起來? –

+0

String s = Path.combine(「@」\\?\「,filePath) – James

+0

和's = @」\\?\「+ filePath'?這是否工作? –

回答

1

拋出後你可能只是做這樣的事情:

DirectoryInfo di = new DirectoryInfo(rootFolder); 
foreach (FileInfo finfo in di.GetFiles("*.*", SearchOption.AllDirectories) 
{ 
    folderSize += finfo.Length; 
} 
+0

它會拋出一個異常,如果有一個快捷方式無法找到父母 – James

0

試試這個:

string path = @"\\Server\Share"; 

System.IO.DirectoryInfo dInfo = new System.IO.DirectoryInfo(path); 
long totalSize = 0; 

foreach (FileInfo fInfo in dInfo.GetFiles("*", SearchOption.AllDirectories)) { 
    totalSize += fInfo.Length; 

} 

Console.Out.WriteLine(totalSize.ToString()); 
+0

它會拋出一個異常,如果有一個快捷方式它找不到父母 – James

+0

你的意思是一個不再存在的文件的快捷方式?因爲它工作完全fi ne對我來說,死亡快捷方式 – Seph

+0

我已更新我原來的帖子,拋出異常被拋出 – James