2014-04-03 26 views
0

我試圖在應用程序第一次啓動時設置一些默認設置。我嘗試和檢測當字符串等於null,但它一直拋出異常錯誤,有什麼想法?當String等於NULL時發生異常錯誤

// Code to execute when the application is launching (eg, from Start) 
// This code will not execute when the application is reactivated 
private void Application_Launching(object sender, LaunchingEventArgs e) 
{ 
    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings; 

    String isFirstRun = settings["firstrun"] as string; 

    if (isFirstRun == null) 
    { 
     settings["firstrun"] = "no"; 
     settings["defaultLocation"] = "Dulles, VA"; 
     settings["defaultTest"] = "Speed Test"; 
     settings.Save(); 
    } 
} 

異常錯誤是:

MyConnection.DLL MyConnection.App.RootFrame_NavigationFailed(對象發件人,System.Windows.Navigation.NavigationFailedEventArgs E)線103 C#

+0

在嘗試將其轉換爲字符串之前,首先檢查'settings [「firstrun」]是否爲'null'。更好的是,不要拋棄它...... – Liel

+2

「但它一直拋出一個異常錯誤」 - 正是什麼異常? –

+0

我已經從問題標題中刪除標籤 - 請注意比大多數情況下的問題[不應在標題中包含標籤](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-在-其-標題)。 – Romasz

回答

2

您!在使用之前,應首先將字典(IS)添加密鑰 - 檢查IS是否包含第一次運行的密鑰:

IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings; 

if (!settings.Contains("firstrun")) 
{ 
    settings.Add("firstrun", "no"); 
    settings.Add("defaultLocation", "Dulles, VA"); 
    settings.Add("defaultTest", "Speed Test"); 
    settings.Save(); 
} 
+0

我試過上面的代碼(請參閱我的開場白問題編輯),沒有運氣。我在App.cs中這樣做,是否會導致問題? –

+0

不知道爲什麼這不起作用我第一次嘗試它!但是,謝謝你,當然,正確的解決方案 –

+0

@DanJamesPalmer我希望你找到了解決方案。這個代碼應該在App第一次運行時運行(稍後你應該用'[「」]'替換那些'Add'(修改鍵值)。至於檢查你也可以嘗試給我們[IsApplicationPreserved](http ://msdn.microsoft.com/en-us/library/windowsphone/develop/ff817008(v = vs.105).aspx) - 但您應該意識到它也會從Tombstone模式返回false。 – Romasz

相關問題