我正在尝试使用以下代码编写一个应用程序来计算一组共享的大小。然而问题是,当搜索深入到共享时,循环中的文件路径变量变得很大,异常会被抛出,因此无法继续。我找到了一些东西,说组合@"\\?\"
允许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 :(得分:1)
你可以这样做:
DirectoryInfo di = new DirectoryInfo(rootFolder);
foreach (FileInfo finfo in di.GetFiles("*.*", SearchOption.AllDirectories)
{
folderSize += finfo.Length;
}
答案 1 :(得分: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());