2011-09-21 105 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