質問

I am trying to find a way to download an XML file on a windows phone which will later on be parsed to be used in a collection. Now I tried the same method I did with the WPF app which is:

public void downloadXml()
{
    WebClient webClient = new WebClient();
    Uri StudentUri = new Uri("url");
    webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(fileDownloaded);
    webClient.DownloadFileAsync(StudentUri, @"C:/path");
}

When moving it to the Windows Phone the webclient loses the DownloadFileAsync and DownloadFileCompleted function. So is there another way of doing this and will I have to use IsolatedStorageFile, if so how can a parse it?

役に立ちましたか?

解決

I tried to reproduce your problem on my machine, but didn't find WebClient class at all. So I use WebRequest instead.

So, the first guy is the helper class for WebRequest:

   public static class WebRequestExtensions
    {
        public static async Task<string> GetContentAsync(this WebRequest request)
        {
            WebResponse response = await request.GetResponseAsync();
            using (var s = response.GetResponseStream())
            {
                using (var sr = new StreamReader(s))
                {
                    return sr.ReadToEnd();
                }
            }
        }
    }

The second guy is the helper class for IsolatedStorageFile:

public static class IsolatedStorageFileExtensions
{
    public static void WriteAllText(this IsolatedStorageFile storage, string fileName, string content)
    {
        using (var stream = storage.CreateFile(fileName))
        {
            using (var streamWriter = new StreamWriter(stream))
            {
                streamWriter.Write(content);
            }
        }
    }

    public static string ReadAllText(this IsolatedStorageFile storage, string fileName)
    {
        using (var stream = storage.OpenFile(fileName, FileMode.Open))
        {
            using (var streamReader = new StreamReader(stream))
            {
                return streamReader.ReadToEnd();
            }
        }
    }
}

And the last piece of solution, the usage example:

private void Foo()
{
    Uri StudentUri = new Uri("uri");

    WebRequest request = WebRequest.Create(StudentUri);

    Task<string> getContentTask = request.GetContentAsync();
    getContentTask.ContinueWith(t =>
    {
        string content = t.Result;

        // do whatever you want with downloaded contents

        // you may save to isolated storage
        IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForAssembly();
        storage.WriteAllText("Student.xml", content);

        // you may read it!
        string readContent = storage.ReadAllText("Student.xml");
        var parsedEntity = YourParsingMethod(readContent);
    });

    // I'm doing my job
    // in parallel
}

Hope this helps.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top