JSON является Объектная нотация JavaScript. Это - очень компактный способ передать наборы данных через сетевые соединения по сравнению с XML. Я предлагаю, чтобы JSON использовались в любых подобных AJAX приложениях, где XML иначе был бы "рекомендуемой" опцией. Многословие XML добавит ко времени загрузки и увеличенному потреблению пропускной способности ($$$). Можно выполнить тот же эффект с JSON, и его разметка почти исключительно выделена самим данным а не глубинной структуре.
If you use Directory.GetFiles
you can do a recursive seach (using SearchOption.AllDirectories
), but this is a bit flaky anyway (especially if you don't have access to one of the sub-directories) - and might involve a huge single array coming back (warning klaxon...).
I'd be happy with the recursion approach unless I could show (via profiling) a bottleneck; and then I'd probably switch to (single-level) Directory.GetFiles
, using a Queue
to emulate recursion.
Note that .NET 4.0 introduces some enumerator-based file/directory listing methods which save on the big arrays.
Вы можете скрыть свою рекурсию за методом расширения (чтобы избежать проблем, которые Марк выделил с помощью метода GetFiles ()):
public static class UserExtension
{
public static IEnumerable<FileInfo> Walk(this DirectoryInfo directory)
{
foreach(FileInfo file in directory.GetFiles())
{
yield return file;
}
foreach(DirectoryInfo subDirectory in directory.GetDirectories())
{
foreach(FileInfo file in subDirectory.Walk())
{
yield return file;
}
}
}
}
(Возможно, вы захотите добавить некоторую обработку исключений для этого для защищенные папки и т. д.)
Затем:
using static UserExtension;
long totalSize = 0L;
var startFolder = new DirectoryInfo("<path to folder>");
// iteration
foreach(FileInfo file in startFolder.Walk())
{
totalSize += file.Length;
}
// linq
totalSize = di.Walk().Sum(s => s.Length);
В основном тот же код, но, может быть, немного лучше ...
Взгляните на это сообщение:
http://social.msdn.microsoft.com/forums/en-US/vbgeneral/thread/eed54ebe-facd-4305-b64b- 9dbdc65df04e
В принципе, чистого .NET-способа не существует, но есть довольно простой подход COM, поэтому, если вы довольны использованием COM-взаимодействия и привязкой к Windows, это может сработать для вас.
I've been looking some time ago for a function like the one you ask for and from what I've found on the Internet and in MSDN forums, there is no such function.
The recursive way is the only I found to obtain the size of a Folder considering all the files and subfolders that contains.
Здесь мой .NET 4.0 приближается
public static long GetFileSizeSumFromDirectory(string searchDirectory)
{
var files = Directory.EnumerateFiles(searchDirectory);
// get the sizeof all files in the current directory
var currentSize = (from file in files let fileInfo = new FileInfo(file) select fileInfo.Length).Sum();
var directories = Directory.EnumerateDirectories(searchDirectory);
// get the size of all files in all subdirectories
var subDirSize = (from directory in directories select GetFileSizeSumFromDirectory(directory)).Sum();
return currentSize + subDirSize;
}
Или даже лучше:
// get IEnumerable from all files in the current dir and all sub dirs
var files = Directory.EnumerateFiles(searchDirectory,"*",SearchOption.AllDirectories);
// get the size of all files
long sum = (from file in files let fileInfo = new FileInfo(file) select fileInfo .Length).Sum();
Как заметил Габриэль, это будет неудачно, если у вас есть ограниченный каталог в searchDirectory!