0

如果他们在尝试将文件保存到隔离存储时没有网络连接,我想给用户一条错误消息并防止应用程序崩溃。我所拥有的在构建时不会给我一个错误,但是当我尝试保存文件时会崩溃。

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

        }
4

1 回答 1

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 块中放置的任何错误,而不会导致整个应用程序崩溃。

于 2014-06-28T23:30:33.477 回答