wp8 入门到精通 Utilities类 本地存储+异步

public class CCSetting
{
public async static void AddOrUpdateValue<T>(string key, T value)
{
try
{
if (key != null)
{
StorageFolder floder = ApplicationData.Current.LocalFolder;
if (!(await floder.GetFoldersAsync()).Any(a => a.Name == "DrieSet"))
{
await ApplicationData.Current.LocalFolder.CreateFolderAsync("DrieSet");
}
string path = System.IO.Path.Combine("DrieSet", key);

StorageFile file = await floder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting);
using (Stream stream = await file.OpenStreamForWriteAsync())
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
js.WriteObject(stream, value);
}
}
}
catch
{

}

}
public async static Task<T> GetValueOrDefault<T>(string key, T defaultValue)
{
try
{
StorageFolder floder = ApplicationData.Current.LocalFolder;
string path = System.IO.Path.Combine("DrieSet", key);
if (!(await floder.GetFoldersAsync()).Any(a => a.Name == "DrieSet"))
{
return defaultValue;
}
else
{
using (Stream istream = await floder.OpenStreamForReadAsync(path))
{
if (istream.Length != 0)
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
return (T)js.ReadObject(istream);
}
}
}
}
catch { }
return defaultValue;
}

public async static void RemoveKey(string key)
{
try
{
StorageFolder floder = ApplicationData.Current.LocalFolder;
string path = System.IO.Path.Combine("DrieSet", key);
if (await CheckFileExit(path))
{
StorageFile file = await floder.GetFileAsync(path);
await file.DeleteAsync();
}
}
catch { }
}

public async static Task<bool> CheckFileExit(string fileName)
{
bool b = false;
if ((await ApplicationData.Current.LocalFolder.GetFoldersAsync()).Any(a => a.Name == "DrieSet"))
{
StorageFolder folder = await ApplicationData.Current.LocalFolder.GetFolderAsync("DrieSet");
b = (await folder.GetFilesAsync()).Any(a => a.Name == fileName);
}
else
{
await ApplicationData.Current.LocalFolder.CreateFolderAsync("DrieSet");
b = false;
}
return b;
}

}

internal class FolderHelper
{
const string PhoneStorage = "C:\\Data\\Users\\Public\\Pictures";
const string SDCardStorage = "D:\\";

/// <summary>
/// 获取手机存储设备的容量信息
/// </summary>
/// <param name="type">存储设备类型</param>
/// <returns>存储设备的容量信息</returns>
///
/// <exception cref="如果设备并不支持SD卡, 那么调用SD内存的时候会导致Exception, 记得try...catch..."/>
public static async Task<StorageSpaceInfo> GetStorageSpaceInfo(StorageTypeEnum type)
{
string rootPath;
switch (type)
{
case StorageTypeEnum.SDCard:
rootPath = SDCardStorage;
break;
default:
rootPath = PhoneStorage;
break;
}

StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(rootPath);
BasicProperties properties = await folder.GetBasicPropertiesAsync();
IDictionary<string, object> filteredProperties =
await properties.RetrievePropertiesAsync(
new[] {
"System.FreeSpace",
"System.Capacity",
"System.FileCount"
});

var capacity = filteredProperties["System.Capacity"];
if (capacity == null)
return null;

var freeSpace = filteredProperties["System.FreeSpace"];
if (freeSpace == null)
return null;

var fileCount = filteredProperties["System.FileCount"];

return new StorageSpaceInfo((ulong)capacity, (ulong)freeSpace);
}
}

/// <summary>
/// 存储设备的容量信息
/// </summary>
internal class StorageSpaceInfo
{
public ulong CapacityByte { get; private set; }
public ulong FreeSpaceByte { get; private set; }
public ulong UsageByte { get; private set; }
public string CapacityString { get; private set; }
public string FreeSpaceString { get; private set; }
public string UsageString { get; private set; }

public StorageSpaceInfo(ulong capacity, ulong freeSpace)
{
CapacityByte = capacity;
FreeSpaceByte = freeSpace;
UsageByte = capacity - freeSpace;

CapacityString = ConvertFileSize(CapacityByte);
FreeSpaceString = ConvertFileSize(FreeSpaceByte);
UsageString = ConvertFileSize(UsageByte);
}

/// <summary>
/// 将以byte为单位的文件大小转换成合适的显示字符串
/// 例:1024000byte -> 1000 KB
/// </summary>
/// <param name="size">文件大小 单位 : bytes</param>
/// <returns></returns>
string ConvertFileSize(double size)
{
string unit = "KB";
double thresholdValue = 1024;

double result = size / thresholdValue;

//MB单位
if (result > thresholdValue)
{
result = result / thresholdValue;
unit = "MB";
}

//GB单位
if (result > thresholdValue)
{
result = result / thresholdValue;
unit = "GB";
}

//TB单位
if (result > thresholdValue)
{
result = result / thresholdValue;
unit = "TB";
}

return string.Format("{0} {1}", result.ToString("f2"), unit);
}
}

enum StorageTypeEnum
{
Phone,
SDCard
}

wp8 入门到精通 Utilities类 本地存储+异步,布布扣,bubuko.com

时间: 2024-08-01 10:32:21

wp8 入门到精通 Utilities类 本地存储+异步的相关文章

wp8 入门到精通 测量代码执行时间

Stopwatch time = new Stopwatch(); byte[] target = new byte[size]; for (int j = 0; j < size; j++) target[j] = unchecked((byte)j); //Otherwise parts of the array are optimised out. CCMD5Core.GetHash(target); time.Start(); for (int i = 1; i <= iteratio

wp8 入门到精通 输入框

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <TextBlock Text="Default" Height="30" HorizontalAlignment="Left" Margin="10,15,0,0" Name="textDefault" Ve

wp8 入门到精通 高仿微信发信息 键盘不消失

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <StackPanel Orientation="Vertical"> <TextBlock Text="Hides soft keyboard on enter:" /> <TextBox x:Name="textBox"

wp8 入门到精通 启动系统分享照片任务

PhotoChooserTask photoChooserTask = new PhotoChooserTask(); photoChooserTask.Completed += photoChooserTask_Completed; photoChooserTask.ShowCamera = true; photoChooserTask.Show(); void photoChooserTask_Completed(object sender, PhotoResult e) { if (e.T

wp8 入门到精通 ---转换

/// <summary>        /// 颜色字符串转Color        /// </summary>        public static Color ConvertFromString(string argb)        {            uint result;            if (uint.TryParse(argb.TrimStart('#', '0'), NumberStyles.HexNumber, null, out resu

wp8 入门到精通 MultiMsgPrompt

List<NotifyMsg> arraymsg = new List<NotifyMsg>(); List<NotifyInfo> ArrayNotifyInfo = new List<NotifyInfo>() { new NotifyInfo(){title="[收信宝]开通失败",content="您的[收信宝]服务未能开通,请重试或联系客服确认订单.{失败原因:失败原因,新快捷支付:支付失败,请重新支付,或联系客服确认

wp8 入门到精通 ImageCompress 图片压缩

//实例化选择器 PhotoChooserTask photoChooserTask = new PhotoChooserTask(); BitmapImage bimg; int newPixelWidth; int newPixelHeight; //构造函数里 //从页面读取输入值作为目标分辨率 newPixelHeight = int.Parse(textBox2.Text.ToString()); //从页面读取输入值作为目标分辨率 newPixelHeight = int.Parse

wp8 入门到精通 Gallery

<Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.Resources> <Style TargetType="Image"> <Setter Property="Margin" Value="-12,-36,0,0"/> </Style> </Grid.Resources>

wp8 入门到精通 定时更新瓷贴

public class ScheduledAgent : ScheduledTaskAgent { static ScheduledAgent() { Deployment.Current.Dispatcher.BeginInvoke(delegate { Application.Current.UnhandledException += UnhandledException; }); } private static void UnhandledException(object sender