C#-扩展StorageFile类以添加自定义字符串属性
在我的windows应用商店应用程序中,我以以下方式保存文件:C#-扩展StorageFile类以添加自定义字符串属性,c#,C#,在我的windows应用商店应用程序中,我以以下方式保存文件: StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName.Replace('/', '_'), CreationCollisionOption.GenerateUniqueName); 现在我想在文件中添加一个标识符,一个字符串,这样我就可以在以后访问这个属性了 我想重写CreateFi
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 }
}
}
public类MyStorageFolder:StorageFolder
{
公共异步任务CreateFileAsync(字符串x)
{
MyStorageFile=(MyStorageFile)等待ApplicationData.Current.LocalFolder.CreateFileAsync(x.Replace(“/”,“"”);
返回文件;
}
}
公共类MyStorageFile:StorageFile
{
私有字符串_objectId=string.Empty;
公共字符串ObjectId
{
获取{返回此。\u objectId;}
设置{this.\u objectId=value}
}
}
我收到一个错误“无法将类型StorageFile转换为MyStorageFile”…有没有办法做到这一点
[编辑]:非常有趣…在运行时,我收到一个错误:'MyStorageFolder':无法从密封类型'StorageFolder'派生…因此我需要一种完全替代的方法来存储我需要的信息
公共类MyStorageFile{
StorageFile文件{get;set;}
字符串MyProperty{get;set;}
}
公共类MyStorageFolder:StorageFolder{
公共异步任务CreateFileAsync(字符串x)
{
MyStorageFile=new MyStorageFile();
file.file=(MyStorageFile)等待ApplicationData.Current.LocalFolder.CreateFileAsync(x.Replace(“/”,“"”);
返回文件;
}
}
是的,有。创建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();
}
代码取自以下链接:
是的,但是如果我稍后获得文件localFolder.GetFileAsync(x),我将丢失MyProperty信息!我认为这是正确的解决方案,但是类StorageFile是密封的,所以我无法扩展它…你有什么想法吗?!感谢您的回答…但我不想在文件中写入字符串…我想将一个信息、一个字符串与文件关联,我将在将来使用该信息…如果您引用的此信息可以注入流中并稍后检索,您可以执行类似操作:dataWriter.WriteUInt32(yourId);dataWriter.WriteString(内容);然后在读取时,首先获取int id,然后获取字符串内容。这样,您就可以将流与id关联起来。也许这不是理想的方式,但如果还有其他更优雅的方式,我也愿意学习
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();
}