我正在尝试使用url下载存储在db中的文件。
下面是示例代码下载
var dirMainToCreate = System.IO.Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Constants.AppDirectory);
if (!System.IO.Directory.Exists(dirMainToCreate))
{
System.IO.Directory.CreateDirectory(dirMainToCreate);
}
var dirContentToCreate = System.IO.Path.Combine(dirMainToCreate, contentdirectory);
if (!System.IO.Directory.Exists(dirContentToCreate))
{
System.IO.Directory.CreateDirectory(dirContentToCreate);
}
CrossDownloadManager.Current.PathNameForDownloadedFile = new Func<IDownloadFile, string>(file => {
return Path.Combine(dirContentToCreate, filename);
});
(CrossDownloadManager.Current as DownloadManagerImplementation).IsVisibleInDownloadsUi = true;
文件= CrossDownloadManager.Current.CreateDownloadFile(Constants.Url +“ / Files / GetFile?id =” + fileId,新字典{{“授权”,“承载者” + this.Token}});
CrossDownloadManager.Current.Start(File);
我的问题是文件已成功下载,但无法打开。
我终于使用了另一种方法,使用了[[WebClient
https://www.c-sharpcorner.com/article/how-to-download-files-in-xamarin-forms/ public void DownloadFile(string url, string token, string folder)
{
string pathToNewFolder = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, folder);
Directory.CreateDirectory(pathToNewFolder);
try
{
using (WebClient client = new WebClient())
{
client.Headers.Add("API_KEY", App.Api_key);
client.Headers.Add("Authorization", "Bearer " + token);
using (Stream rawStream = client.OpenRead(url))
{
string fileName = string.Empty;
string contentDisposition = client.ResponseHeaders["content-disposition"];
if (!string.IsNullOrEmpty(contentDisposition))
{
string lookFor = "filename=";
int index = contentDisposition.IndexOf(lookFor, StringComparison.CurrentCultureIgnoreCase);
if (index >= 0)
fileName = contentDisposition.Substring(index + lookFor.Length);
}
string pathToNewFile = Path.Combine(pathToNewFolder, fileName);
client.DownloadFile(url, pathToNewFile);
}
}
}
catch (Exception ex)
{
if (OnFileDownloaded != null)
OnFileDownloaded.Invoke(this, new DownloadEventArgs(false));
}
}
这里唯一的问题是,操作系统没有显示其本机下载进度条,并且在文件下载完成后也没有给出通知