Windows phone 8: how to download an xml file from the Internet and save it locally?

I want to download an xml file from the network and then save it to local storage, but I do not know how to do it. Please help me clearly or give an example. Thank.

+3
source share
1 answer

Downloading a file is a huge subject and can be done in many ways. I assume that you know the Uri of the file you want to download, and you want to keep in mind the local IsolatedStorage .

I will show three examples of how this can be done (there are other ways).

1. The simplest example will load a line through WebClient :

public static void DownloadFileVerySimle(Uri fileAdress, string fileName)
{
   WebClient client = new WebClient();
   client.DownloadStringCompleted += (s, ev) =>
   {
       using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
       using (StreamWriter writeToFile = new StreamWriter(ISF.CreateFile(fileName)))
           writeToFile.Write(ev.Result);
   };
   client.DownloadStringAsync(fileAdress);
}

, (ev.Result - string - ) IsolStorage. - , :

private void Download_Click(object sender, RoutedEventArgs e)
{
   DownloadFileVerySimle(new Uri(@"http://filedress/myfile.txt", UriKind.Absolute), "myfile.txt");
}

2. (, ) WebClient, ( , MSDN, , , ).

Task, Stream :

public static Task<Stream> DownloadStream(Uri url)
{
   TaskCompletionSource<Stream> tcs = new TaskCompletionSource<Stream>();
   WebClient wbc = new WebClient();
   wbc.OpenReadCompleted += (s, e) =>
   {
      if (e.Error != null) tcs.TrySetException(e.Error);
      else if (e.Cancelled) tcs.TrySetCanceled();
      else tcs.TrySetResult(e.Result);
   };
   wbc.OpenReadAsync(url);
   return tcs.Task;
}

- , DownloadStream:

public enum DownloadStatus { Ok, Error };

public static async Task<DownloadStatus> DownloadFileSimle(Uri fileAdress, string fileName)
{
   try
   {
       using (Stream resopnse = await DownloadStream(new Uri(@"http://filedress/myfile.txt", UriKind.Absolute)))
         using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
         {
            if (ISF.FileExists(fileName)) return DownloadStatus.Error;
            using (IsolatedStorageFileStream file = ISF.CreateFile(fileName))
                resopnse.CopyTo(file, 1024);
            return DownloadStatus.Ok;
         }
   }
   catch { return DownloadStatus.Error; }
}

, , :

private async void Downlaod_Click(object sender, RoutedEventArgs e)
{
   DownloadStatus fileDownloaded = await DownloadFileSimle(new Uri(@"http://filedress/myfile.txt", UriKind.Absolute), "myfile.txt");
   switch (fileDownloaded)
   {
       case DownloadStatus.Ok:
            MessageBox.Show("File downloaded!");
            break;
       case DownloadStatus.Error:
       default:
            MessageBox.Show("There was an error while downloading.");
            break;
    }
}

, , ( 150 ).

3. - WebRequest async-, :

Webrequest , Stream:

public static class Extensions
{
    public static Task<Stream> GetRequestStreamAsync(this WebRequest webRequest)
    {
        TaskCompletionSource<Stream> taskComplete = new TaskCompletionSource<Stream>();
        webRequest.BeginGetRequestStream(arg =>
        {
            try
            {
                Stream requestStream = webRequest.EndGetRequestStream(arg);
                taskComplete.TrySetResult(requestStream);
            }
            catch (Exception ex) { taskComplete.SetException(ex); }
        }, webRequest);
        return taskComplete.Task;
    }
}

:

public static async Task<DownloadStatus> DownloadFile(Uri fileAdress, string fileName)
{
   try
   {
      WebRequest request = WebRequest.Create(fileAdress);
      if (request != null)
      {
          using (Stream resopnse = await request.GetRequestStreamAsync())
          {
             using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
             {
                  if (ISF.FileExists(fileName)) return DownloadStatus.Error;
                    using (IsolatedStorageFileStream file = ISF.CreateFile(fileName))
                    {
                       const int BUFFER_SIZE = 10 * 1024;
                       byte[] buf = new byte[BUFFER_SIZE];

                       int bytesread = 0;
                       while ((bytesread = await resopnse.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
                                file.Write(buf, 0, bytesread);
                   }
             }
             return DownloadStatus.Ok;
         }
     }
     return DownloadStatus.Error;
  }
  catch { return DownloadStatus.Error; }
}

:

private async void Downlaod_Click(object sender, RoutedEventArgs e)
{
   DownloadStatus fileDownloaded = await DownloadFile(new Uri(@"http://filedress/myfile.txt", UriKind.Absolute), "myfile.txt");
   switch (fileDownloaded)
   {
       case DownloadStatus.Ok:
           MessageBox.Show("File downloaded!");
           break;
       case DownloadStatus.Error:
       default:
           MessageBox.Show("There was an error while downloading.");
           break;
   }
}

, , , , , . , , , , . , Background File Transfers - .

, . , , .

, . .

+5

All Articles