Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

c# - How do I get Local folder size in Windows 8.1 (winRT)

I have an Windows 8.1 Store App. I am trying to find the Local Folder Size.?(e.g. 210 MB)

I have an application which would download some of content into my local folder. I want to check the size of my local folder (such as how many MB are currently there).

I have tried looking through MSDN and Google but haven't been able to find anything on it.

Note : I have a folder and subfolder so not only files which is in local folder..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are able to access the LocalFolder via the ApplicationData.LocalFolder property.

This LocalFolder is a StorageFolder object. StorageFolder has a method called GetBasicPropertiesAsync.

GetBasicPropertiesAsync returns a BasicProperties object. This BasicProperties object has a Size property which tells you the size of the item in question (folder or file). I believe that Size is in bytes (a ulong).

The complete command can be done in a single line in an async method like this:

(await ApplicationData.LocalFolder.GetBasicPropertiesAsync()).Size;

You can also split up each step if you need any other information.

Edit: Apparently this does not work as well as hoped. The solution is to create a query and sum up all of the files. You can do this using Linq.

using System.Linq;

// Query all files in the folder. Make sure to add the CommonFileQuery
// So that it goes through all sub-folders as well
var folders = ApplicationData.LocalFolder.CreateFileQuery(CommonFileQuery.OrderByName);

// Await the query, then for each file create a new Task which gets the size
var fileSizeTasks = (await folders.GetFilesAsync()).Select(async file => (await file.GetBasicPropertiesAsync()).Size);

// Wait for all of these tasks to complete. WhenAll thankfully returns each result
// as a whole list
var sizes = await Task.WhenAll(fileSizeTasks);

// Sum all of them up. You have to convert it to a long because Sum does not accept ulong.
var folderSize = sizes.Sum(l => (long) l);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...