用于在IsolatedStorage中存储文件的通用代码

时间:2011-04-01 03:46:30

标签: silverlight windows-phone-7 isolatedstorage

我有一个html文件,其中包含放置在本地位置的图像。要读取这些图像,我使用的是隔离存储。但是在将图像存储在独立存储中时,我需要指定文件名,使我的代码特定于这些文件名例如:我有两个图像abc.jpg和xyz.jpg但是当这些名称变为abc1.jpg和xyz1.jpg时会发生错误。可以用什么来编写不依赖于文件名的通用代码?

2 个答案:

答案 0 :(得分:1)

我这样做:

internal static T LoadFile<T>(string folderName, string filePrefix) where T : class
{
    string fileStreamName = string.Format("{0}\\{1}.dat", folderName, filePrefix);
    return LoadFile<T>(fileStreamName);
}

internal static T LoadFile<T>(string fileStreamName) where T : class
{
    T retval = default(T);

    if (IsoStore.FileExists(fileStreamName))
    {
        using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileStreamName, FileMode.OpenOrCreate, IsoStore))
        {
            if (stream.Length > 0)
            {
                DataContractSerializer dcs = new DataContractSerializer(typeof (T));
                retval = dcs.ReadObject(stream) as T;
            }
        }
    }

    return retval;
}

答案 1 :(得分:0)

一个可能的解决方案是:

您可以使用Resources文件在xap中存储这些文件 - 使用File | New - &gt;资源文件,然后使用资源 - &gt;添加现有文件。

完成此操作后,资源文件将自动为每个资源生成一个公共属性(文本文件的字符串类型,以及二进制文件的byte []类型)。

您可以使用反射列出这些公共属性 - 例如:

    foreach (PropertyInfo pi in MyResources.GetType().GetProperties())
    {
        string propertyName = pi.Name; // the name of your resource
        object propValue = pi.GetValue(o, null); // the value of your resource

        // put your save code here - you might need to use some naming conventions to work out file extensions
    }