2013-10-11 80 views
0

在我的Windows商店應用我保存這樣的文件:C# - 擴展StorageFile類添加自定義字符串屬性

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

我收到錯誤「無法CONVER型StorageFile到MyStorageFile」 ......有沒有辦法做到這一點?!? !我不知道怎麼樣才能保存這些信息,所以我需要一個完整的替代方法來存儲我需要的信息! !

回答

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

} 
+0

是的,但如果我以後得到的文件,localFolder.GetFileAsync(X),我將失去myProperty的信息! – CaptainAmerica

+0

我在想這是正確的解決方案,但StorageFile類是密封的,所以我不能擴展它...你有想法嗎?! – CaptainAmerica

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

+0

謝謝你的回答...但我不想寫一個字符串INTO文件...我想關聯文件信息,一個字符串,我將來會使用... – CaptainAmerica

+0

If你所引用的這些信息可以被注入到流中,稍後你可以做這樣的事情:dataWriter.WriteUInt32(yourId); dataWriter.WriteString(內容);然後在讀取時,首先獲取int id,然後獲取字符串內容。這樣你就可以將你的流與一個id關聯起來。也許不是理想的方式,但如果還有其他更優雅的方式,我也願意學習 – Nostradamus