Xamarin android 保存文本文件 [英] Xamarin android save text file

查看:58
本文介绍了Xamarin android 保存文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Xamarin.Android,我想将 .txt 文件保存到 SD 卡.这是我正在使用的代码:

I am using Xamarin.Android and I want to save a .txt file to the SD card. Here is the code that I am using:

  private void SavetoSd()
  {
       var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
       var filePath = System.IO.Path.Combine(sdCardPath, "iootext.txt");
       if (!System.IO.File.Exists(filePath))
       {
           using(System.IO.StreamWriter write = new System.IO.StreamWriter(filePath,true))
           {
               write.Write(etSipServer.ToString());
           }
       }    
  }

但是,我收到以下错误:

However, I receive the following error:

System.UnauthorizedAccessException:访问路径/mnt/sdcard/iootext.txt"被拒绝.

System.UnauthorizedAccessException: Access to the path "/mnt/sdcard/iootext.txt" is denied.

我已将以下内容添加到清单中:

I have added the following to the manifest:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

如何修复错误?

推荐答案

如果您使用的是 Android 6.0+,则需要执行运行时检查权限.可以这样做:

If you're on Android 6.0+ you will need to perform a runtime check for permissions. This can be done like so:

if ((CheckSelfPermission(Permission.ReadExternalStorage) == (int)Permission.Granted) && 
    (CheckSelfPermission(Permission.WriteExternalStorage) == (int)Permission.Granted))

有关这方面的更多信息可以在 android 文档中找到 此处.

More information on this can be found in the android documentation here.

这篇关于Xamarin android 保存文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆