如果用户在尝试将文件保存到isolatestorage时没有网络连接,我想向用户提供错误消息并防止应用崩溃。我所拥有的不会在构建时给出错误,但在我尝试保存文件时崩溃。
private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LongListSelector selector = sender as LongListSelector;
// verifying our sender is actually a LongListSelector
if (selector == null)
return;
SoundData data = selector.SelectedItem as SoundData;
// verifying our sender is actually SoundData
if (data == null)
return;
if (data.IsDownloaded)
{
if (audioStream != null)
{
audioStream.Close();
audioStream.Dispose();
}
audioStream = IsolatedStorageFile.GetUserStoreForApplication().OpenFile(data.SavePath, FileMode.Open, FileAccess.Read, FileShare.Read);
AudioPlayer.SetSource(audioStream);
AudioPlayer.Play();
}
else
{
WebClient client = new WebClient();
client.OpenReadCompleted += (senderClient, args) =>
{
using (IsolatedStorageFileStream fileStream = IsolatedStorageFile.GetUserStoreForApplication().CreateFile(data.SavePath))
{
if (args == null || args.Cancelled || args.Error != null)
{
MessageBox.Show("Please check your network/cellular connection. If you have a network connection, verify that you can reach drobox.com");
return;
}
args.Result.Seek(0, SeekOrigin.Begin);
args.Result.CopyTo(fileStream);
AudioPlayer.SetSource(fileStream);
AudioPlayer.Play();
}
};
client.OpenReadAsync(new Uri(data.FilePath));
}
答案 0 :(得分:2)
为什么不尝试在尝试使用之前检查参数?
using (IsolatedStorageFileStream fileStream = IsolatedStorageFile.GetUserStoreForApplication().CreateFile(data.SavePath))
{
if (args == null || args.Cancelled || args.Error != null)
{
MessageBox.Show("No connection");
return;
}
args.Result.Seek(0, SeekOrigin.Begin);
args.Result.CopyTo(fileStream);
AudioPlayer.SetSource(fileStream);
AudioPlayer.Play();
}
或者像user574632所说的那样,将整个东西包装在try / catch中。这将允许它正常失败,这样用户就可以看到你在catch块中输入的任何错误,而不会导致整个应用程序崩溃。