1: // Pretend like Item info below just contains a couple pieces of info:
2: // like Uri, Method, and possible a filename to save to --in IsoStorage
3: void downloadSomething(UriInfo item) { 4: var webReq = HttpWebRequest.CreateHttp(UriInfo);
5: webReq.Method = item.UriMethod;
6: WebRequests.Add(item, webReq);
7: // If we were passing post values to the routine we would need to
8: // Begin getting the request stream with a callback and then End Getting
9: // the request stream (this is bad enough.. don't want to overcomplicate things)
10: webReq.BeginGetResponse(ResponseCallback, item);
11: }
12: protected void ResponseCallback(IAsyncResult ar) { 13: IFileItem item= (IFileItem) ar.AsyncState;
14: var webR = WebRequests[item];
15: var resp = (HttpWebResponse) webR.EndGetResponse(ar);
16:
17: if (resp.StatusCode == HttpStatusCode.OK) { 18: // We could also do the whole Begin/End on the Response Stream
19: // (with another calllback)
20: using (var strm = resp.GetResponseStream()) { 21: var buffer = new byte[4096];
22: item.BytesDownloaded = 0;
23: // If the file exists we need to delete it (BTW, using Jay's IsolatedStorage Facade which looks like System.IO.File, Directory, FileInfo, and DirectoryInfo -- "PS" stands for persisted storage)
24: if (PSFile.Exists(item.DestinationNameAndPath))
25: PSFile.Delete(item.DestinationNameAndPath);
26:
27: // We should actually check to see if the path exists for this file..
28: // BTW, this uses my Isolated Storage Facade classes
29: // (so PSDirectory == SystemDirectory, but just against IsolatedStorage)
30: if (!String.IsNullOrEmpty(System.IO.Path.GetDirectoryName(item.DestinationNameAndPath)) && !PSDirectory.Exists(System.IO.Path.GetDirectoryName(item.DestinationNameAndPath)))
31: PSDirectory.CreateDirectory(System.IO.Path.GetDirectoryName(item.DestinationNameAndPath));
32:
33: using (var fs = PSFile.Create(item.DestinationNameAndPath)) { 34: var fileLength = item.ActualSize;
35: do { 36: int count = strm.Read(buffer, 0, 4096);
37: if (count < 1)
38: break;
39: fs.Write(buffer, 0, count);
40: item.BytesDownloaded += count;
41: } while (true);
42: }
43: item.BytesDownloaded = item.ActualSize;
44: }
45: }
46: //else
47: // We got an error or something. Normally I notify the end user of this (this is left up to you to do on your own)
48:
49: }