C# - 扩展StorageFile类以添加自定义字符串属性

时间:2013-10-11 13:33:47

标签: c#

在我的Windows应用商店中,我以这种方式保存文件:

StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName.Replace('/', '_'),
                CreationCollisionOption.GenerateUniqueName);

现在我想在文件中添加一个标识符,一个字符串,以便我可以在另一个时刻访问该属性。

我想覆盖CreateFileAsync方法,但它不起作用:

public class MyStorageFolder : StorageFolder
{
    public async Task<MyStorageFile> CreateFileAsync(string x)
    {            
        MyStorageFile file =  (MyStorageFile) await ApplicationData.Current.LocalFolder.CreateFileAsync(x.Replace('/', '_'));

        return file;
    }

}

public class MyStorageFile : StorageFile
{
    private string _objectId = string.Empty;
    public string ObjectId
    {
        get { return this._objectId; }
        set { this._objectId = value }
    }
}

我收到错误“无法将StorageFile转换为MyStorageFile”...有没有办法做到这一点?!?!

[编辑]:非常有趣......在运行时我收到一个错误:'MyStorageFolder':无法从密封类型'StorageFolder'派生......所以我需要一种完全替代的方式来存储我需要的信息! !

2 个答案:

答案 0 :(得分:1)

Composition

public class MyStorageFile {
    StorageFile File { get; set; }
    String MyProperty { get; set; }
}

public class MyStorageFolder : StorageFolder {
    public async Task<MyStorageFile> CreateFileAsync(string x)
    {             
        MyStorageFile file = new MyStorageFile();         
        file.File =  (MyStorageFile) await ApplicationData.Current.LocalFolder.CreateFileAsync(x.Replace('/', '_'));
            return file;
    }

}

答案 1 :(得分:0)

是的。创建StorageFile类扩展并异步读/写您的内容。

async public static Task WriteAllTextAsync(this StorageFile storageFile, string content) 
        { 
            var inputStream = await storageFile.OpenAsync(FileAccessMode.ReadWrite); 
            var writeStream = inputStream.GetOutputStreamAt(0); 
            DataWriter writer = new DataWriter(writeStream); 
            writer.WriteString(content); 
            await writer.StoreAsync(); 
            await writeStream.FlushAsync(); 
        }

代码取自以下链接: http://dotnetspeak.com/2011/10/reading-and-writing-files-in-winrt