.net开发安卓入门-文件操作与配置操作
- 文件操作
- 内部存储
- 代码
- 运行效果
- System.Environment.SpecialFolder枚举类型对应路径表格
- 外部存储(代码和效果见上图)
- 区别
- 缓存SharedPreferences
- 获取SharedPreferences对象
- 方法列表
- 读取配置信息
- 写配置信息
- Assets
- Nlog配置
文件操作
内部存储
使用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
方法
区别
- 外部存储分为专用和公用,专用存储会随着app卸载而删除
- 在没有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);