【问题标题】:Help with size of folder path帮助了解文件夹路径的大小
【发布时间】:2011-09-21 10:16:05
【问题描述】:

我正在尝试编写一个应用程序来使用以下代码计算一组共享的大小。然而问题是,随着搜索深入到共享中,循环中的文件路径变量变得很大,抛出异常,因此无法继续。我发现一些东西说结合@"\\?\" 可以增加字符数,但我不知道如何正确附加它。如您所料,我的分享采用\\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

【问题讨论】:

  • 您是如何尝试将当前路径与这些字符结合起来的?
  • String s = Path.combine("@"\\?\", filePath)
  • 那么s = @"\\?\" + filePath 呢?这行得通吗?
  • 不,因为我无法让转义字符工作:/
  • 无论如何,if (File.Exists(filePath)) 没有意义。

标签: c# .net file-io filesize


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 如果有快捷方式找不到父级,则会抛出异常
【解决方案2】:

试试这个:

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());

【讨论】:

  • 如果有快捷方式找不到父级,则会抛出异常
  • 您的意思是指向不再存在的文件的快捷方式?因为它对我来说非常适合使用死捷径
  • 我已经更新了我原来的帖子,但抛出了异常
  • 奇怪,我尝试过的一切,包括文件夹权限和访问权限以及指向许多不存在的文件,对我来说一切正常。
  • 这是因为 fileinfo 文件路径太长 - 这与我之前遇到的问题相同
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多