我已经使用xamarin一段时间了,我正在处理的当前项目需要下载一些mp3文件。
我看到了下载文件和下载图片的教程,但他们并没有带我到任何地方,而是为了iOS。
给定网址www.xyz.com/music.mp3
,如何下载mp3文件并保存?
答案 0 :(得分:3)
最简单的方法是使用WebClient,如果在UI线程上,则调用方法DownloadFileTaskAsync:
button.Click += async delegate
{
var destination = Path.Combine(
System.Environment.GetFolderPath(
System.Environment.SpecialFolder.ApplicationData),
"music.mp3");
await new WebClient().DownloadFileTaskAsync(
new Uri("http://www.xyz.com/music.mp3"),
destination);
};
答案 1 :(得分:2)
从下载字符串到下载字节(注意DownloadDataAsync
和DownloadDataCompleted
vs String
兄弟函数)后,Xamarin.iOS docs WebClient
sample for downloading a file应该可以正常工作。
var webClient = new WebClient();
webClient.DownloadDataCompleted += (s, e) => {
var text = e.Result; // get the downloaded text
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = "downloaded.mp3";
string localPath = Path.Combine (documentsPath, localFilename);
File.WriteAllText (localpath, text); // writes to local storage
};
var url = new Uri("http://url.to.some/file.mp3"); // give this an actual URI to an MP3
webClient.DownloadDataAsync(url);
如果您想使用较新的HttpClient
库。在{Xamarin.Android项目中添加对System.Net.Http
的引用,并给出类似的内容。
var url = new Uri("http://url.to.some/file.mp3");
var httpClient = new HttpClient ();
httpClient.GetByteArrayAsync(url).ContinueWith(data => {
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = "downloaded.mp3";
string localPath = Path.Combine (documentsPath, localFilename);
File.WriteAllBytes (localPath, data.Result);
});