C# - 扩展存储文件类以添加自定义字符串属性

本文关键字:添加 自定义 字符串 属性 扩展 存储文件 | 更新日期: 2023-09-27 18:35:09

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

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

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

我想覆盖创建文件异步方法,但它不起作用:

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 }
    }
}

我收到错误"无法将存储文件类型转换为我的存储文件"...有没有办法做到这一点??!?!

[编辑]:真的很有趣...在运行时,我收到一个错误:"我的存储文件夹":无法从密封类型"存储文件夹"派生...所以我需要一种完全替代的方式来存储我需要的信息!!

C# - 扩展存储文件类以添加自定义字符串属性

构图。

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;
    }
}

是的,有。创建存储文件类扩展并异步读取/写入内容。

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