[英]Cannot load nlog.config in Xamarin
我无法读取android平台资产文件夹中的nlog.config文件
NLog.LogManager.Configuration = new XmlLoggingConfiguration("NLog.config");
如何读取nlog文件,并且此文件也在android资源中。
您也可以使用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);
}
另请参阅: https : //github.com/NLog/NLog/wiki/Explicit-NLog-configuration-loading#loading-nlog-configuration-from-xamarin-resource
您也可以尝试使用此代码(带有构建操作的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
您可以在上下文类中添加扩展方法,以将所需的资产作为流获取:
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“ NLog.config”(在此框中)将自动加载。 如果文件名不同,请使用:
LogManager.Configuration = new XmlLoggingConfiguration("assets/someothername.config");
感谢您的答复。 我通过设置autoReload =“ false” throwExceptions =“ false”解决了此问题。 由于这两个原因,我的配置文件不可见。 我不知道它们如何影响文件的可见性,但是将以上两个设置为false我现在可以获取配置文件了,谢谢,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.