.net开发安卓入门-文件操作与配置操作

文件操作

内部存储

使用System.Environment.GetFolderPath方法获取路径

代码

 protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            var txt = FindViewById<TextView>(Resource.Id.txt);
            txt.Append($"ApplicationData:{System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData)} \r\n");
            txt.Append($"LocalApplicationData:{System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData)} \r\n");

            txt.Append($"MyDocuments:{System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments)} \r\n");

            using (var writer = File.CreateText(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "/MyDocuments.txt"))
            {
                writer.WriteLineAsync("MyDocuments").Wait();
            }

            txt.Append($"Personal:{System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)} \r\n");

            txt.Append($"CommonApplicationData:{System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData)} \r\n");

 
            txt.Append($"CacheDir:{this.ApplicationContext.CacheDir.AbsolutePath} \r\n");
            using (var writer = File.CreateText(this.ApplicationContext.CacheDir.AbsolutePath+"/cache.txt"))
            {
                  writer.WriteLineAsync("cache").Wait();
            }
            txt.Append($"DataDir:{this.ApplicationContext.DataDir.AbsolutePath} \r\n");

            using (var writer = File.CreateText(this.ApplicationContext.DataDir.AbsolutePath + "/data.txt"))
            {
                writer.WriteLineAsync("data").Wait();
            }

            txt.Append("data文件内容:" + File.ReadAllText(this.ApplicationContext.DataDir.AbsolutePath + "/data.txt"));

            txt.Append($" ---------------------------------------------\r\n");

            txt.Append($"扩展存储操作\r\n");
            txt.Append($"ExternalStorageDirectory:{Android.OS.Environment.ExternalStorageDirectory} \r\n");

            txt.Append($"AbsolutePath:{Environment.DataDirectory.AbsolutePath} \r\n");
            txt.Append($"root:{this.ApplicationContext.GetExternalFilesDir("root")} \r\n");
            txt.Append($"null:{this.ApplicationContext.GetExternalFilesDir(null)} \r\n");

            txt.Append($"cache:{string.Join(" , " ,this.ApplicationContext.GetExternalCacheDirs().Select(t=>t.AbsolutePath))} \r\n");
        }

运行效果

在这里插入图片描述

System.Environment.SpecialFolder枚举类型对应路径表格

在这里插入图片描述

外部存储(代码和效果见上图)

外部存储主要使用this.ApplicationContext.GetExternalFilesDir方法

针对于外部存储比较容易混淆,因为在Android4.4以前,手机机身存储就叫内部存储,插入的SD卡就是外部存储,但是在Android4.4以后的话,就目前而言,现在的手机自带的存储就很大,现在Android10.0的话,有的手机能达到256G的存储,针对于这种情况,手机机身自带的存储也是外部存储,如果再插入SD卡的话也叫外部存储,因此对于外部存储分为两部分:SD卡和扩展卡内存

区别

  1. 外部存储分为专用和公用,专用存储会随着app卸载而删除
  2. 在没有root的情况,通过安卓系统的文件管理功能,是无法查看内部存储的,外部存储在文件–>Android–>data–>“APP名称”

缓存SharedPreferences

SharedPreferences是Android平台上一个轻量级的存储辅助类,用来保存应用的一些常用配置,它提供了String,set,int,long,float,boolean六种数据类型。SharedPreferences的数据以键值对的进行保存在以xml形式的文件中。在应用中通常做一些简单数据的持久化缓存。

获取SharedPreferences对象

在Activity中 GetSharedPreferences(“一个名字”, FileCreationMode.Private);获取sp对象

方法列表


using System;
using System.Collections.Generic;
using Android.Runtime;
using Java.Interop;

namespace Android.Content
{
    //
    // 摘要:
    //     Interface for accessing and modifying preference data returned by Context#getSharedPreferences.
    //
    // 言论:
    //     Java documentation for
    //     android.content.SharedPreferences
    //     .
    //     Portions of this page are modifications based on work created and shared by the
    //     Android Open Source Project and used according to terms described in the Creative
    //     Commons 2.5 Attribution License.
    [Register("android/content/SharedPreferences", "", "Android.Content.ISharedPreferencesInvoker")]
    public interface ISharedPreferences : IJavaObject, IDisposable, IJavaPeerable
    {
        //
        // 摘要:
        //     Retrieve all values from the preferences.
        //
        // 值:
        //     To be added.
        //
        // 异常:
        //   T:Java.Lang.NullPointerException:
        //
        // 言论:
        //     Portions of this page are modifications based on work created and shared by the
        //     Android Open Source Project and used according to terms described in the Creative
        //     Commons 2.5 Attribution License.
        IDictionary<string, object>? All
        {
            [Register("getAll", "()Ljava/util/Map;", "GetGetAllHandler:Android.Content.ISharedPreferencesInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")]
            get;
        }

        //
        // 摘要:
        //     Checks whether the preferences contains a preference.
        //
        // 参数:
        //   key:
        //     The name of the preference to check.
        //
        // 返回结果:
        //     Returns true if the preference exists in the preferences, otherwise false.
        //
        // 言论:
        //     Java documentation for
        //     android.content.SharedPreferences.contains(java.lang.String)
        //     .
        //     Portions of this page are modifications based on work created and shared by the
        //     Android Open Source Project and used according to terms described in the Creative
        //     Commons 2.5 Attribution License.
        [Register("contains", "(Ljava/lang/String;)Z", "GetContains_Ljava_lang_String_Handler:Android.Content.ISharedPreferencesInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")]
        bool Contains(string? key);

        //
        // 摘要:
        //     Create a new Editor for these preferences, through which you can make modifications
        //     to the data in the preferences and atomically commit those changes back to the
        //     SharedPreferences object.
        //
        // 返回结果:
        //     Returns a new instance of the Editor interface, allowing you to modify the values
        //     in this SharedPreferences object.
        //
        // 言论:
        //     Java documentation for
        //     android.content.SharedPreferences.edit()
        //     .
        //     Portions of this page are modifications based on work created and shared by the
        //     Android Open Source Project and used according to terms described in the Creative
        //     Commons 2.5 Attribution License.
        [Register("edit", "()Landroid/content/SharedPreferences$Editor;", "GetEditHandler:Android.Content.ISharedPreferencesInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")]
        ISharedPreferencesEditor? Edit();

        //
        // 摘要:
        //     Retrieve a boolean value from the preferences.
        //
        // 参数:
        //   key:
        //     The name of the preference to retrieve.
        //
        //   defValue:
        //     Value to return if this preference does not exist.
        //
        // 返回结果:
        //     To be added.
        //
        // 异常:
        //   T:Java.Lang.ClassCastException:
        //
        // 言论:
        //     Portions of this page are modifications based on work created and shared by the
        //     Android Open Source Project and used according to terms described in the Creative
        //     Commons 2.5 Attribution License.
        [Register("getBoolean", "(Ljava/lang/String;Z)Z", "GetGetBoolean_Ljava_lang_String_ZHandler:Android.Content.ISharedPreferencesInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")]
        bool GetBoolean(string? key, bool defValue);

        //
        // 摘要:
        //     Retrieve a float value from the preferences.
        //
        // 参数:
        //   key:
        //     The name of the preference to retrieve.
        //
        //   defValue:
        //     Value to return if this preference does not exist.
        //
        // 返回结果:
        //     To be added.
        //
        // 异常:
        //   T:Java.Lang.ClassCastException:
        //
        // 言论:
        //     Portions of this page are modifications based on work created and shared by the
        //     Android Open Source Project and used according to terms described in the Creative
        //     Commons 2.5 Attribution License.
        [Register("getFloat", "(Ljava/lang/String;F)F", "GetGetFloat_Ljava_lang_String_FHandler:Android.Content.ISharedPreferencesInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")]
        float GetFloat(string? key, float defValue);

        //
        // 摘要:
        //     Retrieve an int value from the preferences.
        //
        // 参数:
        //   key:
        //     The name of the preference to retrieve.
        //
        //   defValue:
        //     Value to return if this preference does not exist.
        //
        // 返回结果:
        //     To be added.
        //
        // 异常:
        //   T:Java.Lang.ClassCastException:
        //
        // 言论:
        //     Portions of this page are modifications based on work created and shared by the
        //     Android Open Source Project and used according to terms described in the Creative
        //     Commons 2.5 Attribution License.
        [Register("getInt", "(Ljava/lang/String;I)I", "GetGetInt_Ljava_lang_String_IHandler:Android.Content.ISharedPreferencesInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")]
        int GetInt(string? key, int defValue);

        //
        // 摘要:
        //     Retrieve a long value from the preferences.
        //
        // 参数:
        //   key:
        //     The name of the preference to retrieve.
        //
        //   defValue:
        //     Value to return if this preference does not exist.
        //
        // 返回结果:
        //     To be added.
        //
        // 异常:
        //   T:Java.Lang.ClassCastException:
        //
        // 言论:
        //     Portions of this page are modifications based on work created and shared by the
        //     Android Open Source Project and used according to terms described in the Creative
        //     Commons 2.5 Attribution License.
        [Register("getLong", "(Ljava/lang/String;J)J", "GetGetLong_Ljava_lang_String_JHandler:Android.Content.ISharedPreferencesInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")]
        long GetLong(string? key, long defValue);

        //
        // 摘要:
        //     Retrieve a String value from the preferences.
        //
        // 参数:
        //   key:
        //     The name of the preference to retrieve.
        //
        //   defValue:
        //     Value to return if this preference does not exist.
        //
        // 返回结果:
        //     To be added.
        //
        // 异常:
        //   T:Java.Lang.ClassCastException:
        //
        // 言论:
        //     Portions of this page are modifications based on work created and shared by the
        //     Android Open Source Project and used according to terms described in the Creative
        //     Commons 2.5 Attribution License.
        [Register("getString", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", "GetGetString_Ljava_lang_String_Ljava_lang_String_Handler:Android.Content.ISharedPreferencesInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")]
        string? GetString(string? key, string? defValue);

        //
        // 摘要:
        //     To be added.
        //
        // 参数:
        //   key:
        //     To be added.
        //
        //   defValues:
        //     To be added.
        //
        // 返回结果:
        //     To be added.
        //
        // 言论:
        //     Portions of this page are modifications based on work created and shared by the
        //     Android Open Source Project and used according to terms described in the Creative
        //     Commons 2.5 Attribution License.
        [Register("getStringSet", "(Ljava/lang/String;Ljava/util/Set;)Ljava/util/Set;", "GetGetStringSet_Ljava_lang_String_Ljava_util_Set_Handler:Android.Content.ISharedPreferencesInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")]
        ICollection<string>? GetStringSet(string? key, ICollection<string>? defValues);

        //
        // 摘要:
        //     Registers a callback to be invoked when a change happens to a preference.
        //
        // 参数:
        //   listener:
        //     The callback that will run.
        //
        // 言论:
        //     Java documentation for
        //     android.content.SharedPreferences.registerOnSharedPreferenceChangeListener(android.content.OnSharedPreferenceChangeListener)
        //     .
        //     Portions of this page are modifications based on work created and shared by the
        //     Android Open Source Project and used according to terms described in the Creative
        //     Commons 2.5 Attribution License.
        [Register("registerOnSharedPreferenceChangeListener", "(Landroid/content/SharedPreferences$OnSharedPreferenceChangeListener;)V", "GetRegisterOnSharedPreferenceChangeListener_Landroid_content_SharedPreferences_OnSharedPreferenceChangeListener_Handler:Android.Content.ISharedPreferencesInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")]
        void RegisterOnSharedPreferenceChangeListener(ISharedPreferencesOnSharedPreferenceChangeListener? listener);

        //
        // 摘要:
        //     Unregisters a previous callback.
        //
        // 参数:
        //   listener:
        //     The callback that should be unregistered.
        //
        // 言论:
        //     Java documentation for
        //     android.content.SharedPreferences.unregisterOnSharedPreferenceChangeListener(android.content.OnSharedPreferenceChangeListener)
        //     .
        //     Portions of this page are modifications based on work created and shared by the
        //     Android Open Source Project and used according to terms described in the Creative
        //     Commons 2.5 Attribution License.
        [Register("unregisterOnSharedPreferenceChangeListener", "(Landroid/content/SharedPreferences$OnSharedPreferenceChangeListener;)V", "GetUnregisterOnSharedPreferenceChangeListener_Landroid_content_SharedPreferences_OnSharedPreferenceChangeListener_Handler:Android.Content.ISharedPreferencesInvoker, Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")]
        void UnregisterOnSharedPreferenceChangeListener(ISharedPreferencesOnSharedPreferenceChangeListener? listener);
    }
}

读取配置信息

 var sp = GetSharedPreferences(Resource.String.app_name.ToString(), FileCreationMode.Private);
           
Common.HostUrl = sp.GetString("Host", null);
Common.CarNum= sp.GetString("CarNumber", "999"); 

写配置信息

  var sp = GetSharedPreferences(Resource.String.app_name.ToString(), FileCreationMode.Private);
  sp.Edit().PutString("CarNumber", Common.CarNum).Commit();

Assets

如果程序中有一些固定的配置文件,例如NLog中的nlog.config,或者一些不需要写入的才可以,因为Assets是只能读,不能写的。

Nlog配置

在Assets文件夹中添加nlog.config文件,在属性中将Build Action设置为AndroidAsset

var steam = Assets.Open("nlog.config");
var xmlReader = System.Xml.XmlReader.Create(steam);
NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(xmlReader, null);

Xamarin Android
⚠️ NLog v5 will no longer scan the assets folder for NLog.config. Instead consider using Xamarin Assembly Resource

*With NLog v4 then the NLog.dll built for Xamarin Android would automatically scan the assets folder for NLog.config.
If the file name is different, then NLog v4 also supported this:
LogManager.Configuration = new XmlLoggingConfiguration(“assets/someothername.config”);
If using the NLog.dll built for NetStandard in Xamarin, then the Android assets-folder is not recognized or scanned. Instead consider using Assembly Resource.
To explicly read file from Android Assets, then one can do this:
AssetManager assets = this.Assets;

var assetStream = assets.Open("NLog.config");
var xmlReader = System.Xml.XmlReader.Create(assetStream);
NLog.LogManager.Configuration = new XmlLoggingConfiguration(xmlReader, null);

同系列文章推荐

.net开发安卓入门 - 环境安装
.net开发安卓入门 - Hello world!
.net开发安卓入门 - 基本交互(Button,输入EditText,TextView,Toast)
.net开发安卓入门 - 布局与样式
.net开发安卓入门 - Activity
.net开发安卓入门 - Notification(通知)
.net开发安卓入门 - 四大基本组件
.net开发安卓入门 - Service (服务)
.net开发安卓入门 - 打包(.apk)
.net开发安卓入门 - ImageView 显示网络图片
.net开发安卓入门-文件操作与配置操作
.net开发安卓入门-Dialog
.net开发安卓入门-自动升级(配合.net6 webapi 作为服务端)
vs2022 实现无线调试安卓(Windows)
.net开发安卓从入门到放弃
.net开发安卓从入门到放弃 最后的挣扎(排查程序闪退问题记录-到目前为止仍在继续)
.net开发安卓入门 -记录两个问题处理办法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值