我很头疼使这个工作,是一个mp3下载器,从mp3clan和其他网站下载歌曲。这是我的下载代码:
public void StartDownload()
{
downloadMusicGuid = dwMp3Skull.GenerateUniqueGuid();
streamToWriteTo = new IsolatedStorageFileStream("music/" + downloadMusicGuid + ".mp3", FileMode.Create, file);
request = (HttpWebRequest)WebRequest.Create(URL);
request.AllowReadStreamBuffering = false;
request.BeginGetResponse(new AsyncCallback(GetData), request);
}
void GetData(IAsyncResult result)
{
try
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
Deployment.Current.Dispatcher.BeginInvoke(new Action(() => fSize = BytesToString(response.ContentLength)));
Stream rStream = response.GetResponseStream();
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
byte[] data = new byte[16 * 1024];
int read;
long totalValue = response.ContentLength;
long sum = 0;
while ((read = rStream.Read(data, 0, data.Length)) > 0 )
{
sum += read;
Deployment.Current.Dispatcher.BeginInvoke(new Action(() => Progress = (int)((sum * 100) / totalValue)));
try
{
streamToWriteTo.Write(data, 0, read);
}
catch (ObjectDisposedException ex)
{
return;
}
}
streamToWriteTo.Close();
streamToWriteTo.Dispose();
if (ModelLocator.HomeStatic.Downloads.Count != 0)
{
foreach (Download d in ModelLocator.HomeStatic.Downloads)
{
if (d.State == DownloadState.Pending)
{
d.State = DownloadState.InProgress;
d.StartDownload();
break;
}
}
}
Deployment.Current.Dispatcher.BeginInvoke(new Action(() => ConvertDownloadToTrack(this)));
Deployment.Current.Dispatcher.BeginInvoke(new Action(() => ModelLocator.HomeStatic.Downloads.Remove(this)));
}
catch (Exception ex)
{
Deployment.Current.Dispatcher.BeginInvoke(new Action(() => MessageBox.Show(ex.Message)));
return;
}
}
此代码适用于直接链接,但它不适用于mp3clan.audio,这是一个链接的示例,我已经测试了这个链接,它似乎在返回文件之前重定向到两个网站(i& #39;我不确定):
有人能指出我正确的方向吗?谢谢你的阅读。