我用WebClient
在apk中下载了文件。但是我得到了这个错误:
未处理的异常:
System.Net.WebException:WebClient请求期间发生异常。
这是我尝试过的代码:
{
using (WebClient client = new WebClient())
{
client.DownloadFile(
"https://code.org/images/social-media/code-2018-creativity.png",
@"j:\storage\emulated\legacy\Download\code-2018-creativity.png");
}
}
答案 0 :(得分:0)
由于您仅引用WebException,因此它可能与以下情况之一有关:
BaseAddress
和address
组合而成的URI无效。如果您向我们提供了有关异常的更多信息,我们也许可以将错误减少为以下情况之一。要获得InnerException
,您可以执行以下操作:
{
using (WebClient client = new WebClient ())
{
try
{
client.DownloadFile (
"https://code.org/images/social-media/code-2018-creativity.png",
@"j:\storage\emulated\legacy\Download\code-2018-creativity.png");
}
catch (Exception ex)
{
while (ex != null)
{
Console.WriteLine (ex.Message);
ex = ex.InnerException;
}
}
}
}
答案 1 :(得分:0)
如果您运行的是Android api级别23或更高版本,则即使您在清单文件中提到了运行时权限,也必须询问运行时权限。
看看这个博客将对如何获得运行时许可有所帮助:requesting-runtime-permissions-in-android
这也是如何检查RuntimePermissions
的官方示例引用:xamarin-system-unauthorizedaccessexception-access-to-the-path-is-denied
更新:
要询问运行时权限,您可以使用以下插件:Plugin.Permissions,将其安装到您的项目中。
然后,在下载文件之前调用CheckMyPermissionAsync();
:
private void FabOnClick(object sender, EventArgs eventArgs)
{
View view = (View) sender;
CheckMyPermissionAsync();
}
在方法CheckMyPermissionAsync()
中,检查您的存储权限,然后下载文件:
public async void CheckMyPermissionAsync()
{
var permissionsStartList = new List<Permission>()
{
Permission.Storage
};
var permissionsNeededList = new List<Permission>();
try
{
foreach (var permission in permissionsStartList)
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
if (status != PermissionStatus.Granted)
{
permissionsNeededList.Add(permission);
}
}
}
catch (Exception ex)
{
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(permissionsNeededList.ToArray());
//Check the persimmison again
var storeagePermission = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
if (storeagePermission == PermissionStatus.Granted)
{
//Download file here
DownloadFile("http://www.dada-data.net/uploads/image/hausmann_abcd.jpg", "XF_Downloads");
}
else {
Console.WriteLine("No permissions");
}
}
您可以在完成的事件中查看结果:
private void Completed(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
Console.WriteLine("success");
}
else
{
if (OnFileDownloaded != null) { }
Console.WriteLine("fail");
}
}
注意:注意您的filePath,确保您的路径正确,我使用:
string pathToNewFolder = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, folder);
我在这里更新了示例:runtime-permission-xamarin.android