2014-05-11 2 views
1

나중에 Windows 전화에서 XML 파일을 다운로드하여 컬렉션에서 사용하도록 구문 분석 할 방법을 찾으려고합니다. 윈도우 전화로 이동하면URL에서 XML 다운로드

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

웹 클라이언트가 DownloadFileAsyncDownloadFileCompleted 기능을 상실 : 지금은 내가있는 WPF 응용 프로그램에서했던 같은 방법을 시도했다. 그래서 또 다른 방법이 일을하고 IsolatedStorageFile 사용해야합니다, 그렇다면 어떻게 구문 분석 할 수 있습니까?

+0

파일을 다시 구문 분석하려고 할 때 문자열로 다운로드하지 않으시겠습니까? 나는 webClient.DownloadStringAsync를 의미합니까? – AMS

답변

1

내 컴퓨터에서 문제를 재현하려고했지만 WebClient 클래스를 전혀 찾지 못했습니다. 그래서 대신 WebRequest을 사용합니다.

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

및 솔루션의 마지막 조각, 사용 예 :

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

두 번째 사람은 도우미 IsolatedStorageFile에 대한 클래스는 다음과 같습니다

그래서 첫 번째 사람은 WebRequest의 헬퍼 클래스입니다 :

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 
} 

희망이 있습니다.