2009-07-11 21 views

回答

23

通過使用反射訪問IsolatedStorageFileStream類的專用字段,可以檢索磁盤上獨立存儲文件的路徑。這裏是一個例子:


// Create a file in isolated storage. 
IsolatedStorageFile store = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null); 
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("test.txt", FileMode.Create, store); 
StreamWriter writer = new StreamWriter(stream); 
writer.WriteLine("Hello"); 
writer.Close(); 
stream.Close(); 

// Retrieve the actual path of the file using reflection. 
string path = stream.GetType().GetField("m_FullPath", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(stream).ToString(); 

雖然我不確定這是一個建議的做法。

請記住,磁盤上的位置取決於操作系統的版本,您需要確保其他應用程序有權訪問該位置。

+2

至少在Silverlight 4中,任何嘗試執行此反射都會導致... mscorlib.dll中發生類型'System.FieldAccessException'的第一次機會異常 其他信息:嘗試按方法'Comms.MainPage.LayoutRoot_Loaded (System.Object,System.Windows.RoutedEventArgs)'以訪問字段'System.IO.IsolatedStorage.IsolatedStorageFile.m_StorePath'失敗。此外,它現在是「m_StorePath」而不是「m_FullPath」 - 更不用它的原因。 – DJA 2011-07-21 13:02:21

+0

@DJA這是因爲安全考慮,您無法通過Silverlight中的反射獲得私人成員。 – ghord 2014-07-28 07:22:09

6

而不是創建一個臨時文件並獲得位置的,你可以直接從商店得到的路徑:

var path = store.GetType().GetField("m_RootDir", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(store).ToString(); 
8

我用的FileStream的名稱屬性。

private static string GetAbsolutePath(string filename) 
{ 
    IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication(); 

    string absoulutePath = null; 

    if (isoStore.FileExists(filename)) 
    { 
     IsolatedStorageFileStream output = new IsolatedStorageFileStream(filename, FileMode.Open, isoStore); 
     absoulutePath = output.Name; 

     output.Close(); 
     output = null; 
    } 

    return absoulutePath; 
} 

此代碼已在Windows Phone 8 SDK中測試。

相關問題