在Windows Phone 7应用程序从SkyDrive下载文件时出现NullReferenceException

时间:2013-09-15 20:03:46

标签: windows-phone-7 nullreferenceexception onedrive

我有app应该备份并将其数据库恢复到SkyDrive。 但是,如果我使用“开始”按钮(快速应用程序切换)关闭上传或从SkyDrive下载备份应用程序,然后使用“后退”按钮返回应用程序,我会捕获未处理的NullReferenceException:

void RestoreFromSkyDrive() {
  ShowProgress();

  LiveConnectClient client = new LiveConnectClient(App.Session);
  string id = string.Empty;
  if (client != null) {
    client.GetCompleted += (obj, args) => {
      try {
        List<object> items;

        if (args != null && args.Result != null && args.Result["data"] != null)
          items = args.Result["data"] as List<object>;
        else
          return;

        foreach (object item in items) {
          Dictionary<string, object> file = item as Dictionary<string, object>;
          // fileName is a name of backup-file
          if (file != null && file["name"] != null && file["name"].ToString() == fileName) {
            id = file["id"].ToString();
            if (client != null) client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(client_DownloadCompleted);
            if (client != null) client.DownloadAsync(String.Format("{0}/content", id));
            break;
          }
        }
      }
      catch (Exception ex) {
        MessageBox.Show(ex.Message + " restore");
      }
    };
    if (client != null) {
      client.GetAsync("me/skydrive/files");
    }
  }
}

void client_DownloadCompleted(object sender, LiveDownloadCompletedEventArgs e) {
  try {
    if (e.Error == null) {
      Stream stream = e.Result;

      using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) {
        var fileToSave = new IsolatedStorageFileStream(Constants.dbName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, storage);
        stream.CopyTo(fileToSave);
        stream.Flush();
        stream.Close();
        fileToSave.Close();
      }
    }
    else {
      MessageBox.Show(e.Error.Message + " dcompleted mb");
    }
  }
  catch (WebException ex) { MessageBox.Show(ex.Message + " dcompleted ex"); }
  HideProgress();
}

我为null插入了很多检查,但无论如何我都会捕获NullReferenceException。我不知道我能做些什么。

PS:启用了CLR异常的StackTrace:

System.Net.WebException occurred
Message=WebException
StackTrace:
   at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
   at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClass2.<EndGetResponse>b__1(Object sendState)
   at System.Net.Browser.AsyncHelper.<>c__DisplayClass4.<BeginOnUI>b__0(Object sendState)
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at System.Delegate.DynamicInvokeOne(Object[] args)
   at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at System.Windows.Threading.Dispatcher.<>c__DisplayClass4.<FastInvoke>b__3()
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at System.Delegate.DynamicInvokeOne(Object[] args)
   at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
   at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
   at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
   at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
   at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)

StackTrace with disabled CLR Exceptions:

System.NullReferenceException was unhandled
Message=NullReferenceException
StackTrace:
   at Microsoft.Live.Operations.DownloadOperation.CompleteOperation(Exception error)
   at Microsoft.Live.Operations.DownloadOperation.OnCancel()
   at Microsoft.Live.Operations.WebOperation.OnGetWebResponse(IAsyncResult ar)
   at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.<InvokeGetResponseCallback>b__8(Object state2)
   at System.Threading.ThreadPool.WorkItem.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadPool.WorkItem.doWork(Object o)
   at System.Threading.Timer.ring()

1 个答案:

答案 0 :(得分:0)

使用BackgroundDownload(上传)异步方法而不是下载(上传)Async帮助我。