【发布时间】:2019-08-24 14:05:18
【问题描述】:
我无法读取android平台资产文件夹中的nlog.config文件
NLog.LogManager.Configuration = new XmlLoggingConfiguration("NLog.config");
如何读取 nlog 文件,并且这个文件在 android 资产中。
【问题讨论】:
标签: c# android xamarin logging nlog
我无法读取android平台资产文件夹中的nlog.config文件
NLog.LogManager.Configuration = new XmlLoggingConfiguration("NLog.config");
如何读取 nlog 文件,并且这个文件在 android 资产中。
【问题讨论】:
标签: c# android xamarin logging nlog
您可以将扩展方法添加到上下文类中,以将所需资产作为流获取:
public static class Utils
{
public static Stream GetFromAssets(this Context context, string assetName)
{
AssetManager assetManager = context.Assets;
Stream inputStream;
try
{
using (inputStream = assetManager.Open(assetName))
{
return inputStream;
}
}
catch (Exception e)
{
return null;
}
}
}
然后在您的活动上下文中访问它:
var Asset= context.GetFromAssets("AssetName");
请注意,这将返回 System.IO.Stream。
祝你好运
在查询时还原。
【讨论】:
对于 Xamarin Android,assets 文件夹中的“NLog.config”(在此外壳中)将自动加载。如果文件名不同,则使用:
LogManager.Configuration = new XmlLoggingConfiguration("assets/someothername.config");
【讨论】:
您还可以使用 Xamarin 资源。将 NLog.config 文件放入库项目中,然后编辑文件的属性 - 将构建操作更改为嵌入式资源。
public static Stream GetEmbeddedResourceStream(Assembly assembly, string resourceFileName)
{
var resourcePaths = assembly.GetManifestResourceNames()
.Where(x => x.EndsWith(resourceFileName, StringComparison.OrdinalIgnoreCase))
.ToList();
if (resourcePaths.Count == 1)
{
return assembly.GetManifestResourceStream(resourcePaths.Single());
}
return null;
}
var nlogConfigFile = GetEmbeddedResourceStream(myAssembly, "NLog.config");
if (nlogConfigFile != null)
{
var xmlReader = System.Xml.XmlReader.Create(nlogConfigFile);
NLog.LogManager.Configuration = new XmlLoggingConfiguration(xmlReader, null);
}
【讨论】:
typeof(Program).Assembly
您也可以尝试使用此(nlog.config 文件与构建操作作为 AndroidAsset):
NLog.LogManager.Configuration = new XmlLoggingConfiguration (XmlTextReader.Create(Assets.Open ("NLog.config")), null);
参考: https://github.com/NLog/NLog/blob/master/src/NLog/Config/LoggingConfigurationFileLoader.cs#L101-L120
【讨论】:
感谢您的回复。我通过设置 autoReload="false" throwExceptions="false" 解决了这个问题。由于这两个,我的配置文件不可见。我不知道它们如何影响文件可见性,但将以上两个设置为 false 我现在可以获取配置文件 谢谢,
【讨论】: