Cannot load nlog.config in Xamarin

2019-08-20 01:27发布

I cannot read nlog.config file in asset folder of android platform

NLog.LogManager.Configuration = new XmlLoggingConfiguration("NLog.config");

How to read nlog file and also this file is in android asset.

5条回答
小情绪 Triste *
2楼-- · 2019-08-20 02:15

Thanks for your response. I resolved this issue by setting autoReload="false" throwExceptions="false". Due to these two my config file was not visible. I dont know how they affect the file visibility but setting above two to false i can get config file now Thanks,

查看更多
甜甜的少女心
3楼-- · 2019-08-20 02:25

For Xamarin Android "NLog.config" (in this casing) in the assets folder will be loaded automatically. If the file name is different, then use:

LogManager.Configuration = new XmlLoggingConfiguration("assets/someothername.config");
查看更多
smile是对你的礼貌
4楼-- · 2019-08-20 02:26

You can also make use of Xamarin resource. Put the NLog.config file into the library project, then edit file's properties - change the build action to embedded resource.

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);
}

See also: https://github.com/NLog/NLog/wiki/Explicit-NLog-configuration-loading#loading-nlog-configuration-from-xamarin-resource

查看更多
Juvenile、少年°
5楼-- · 2019-08-20 02:27

you could also try to use this (nlog.config file with a Build Action as an AndroidAsset):

NLog.LogManager.Configuration = new XmlLoggingConfiguration (XmlTextReader.Create(Assets.Open ("NLog.config")), null);

refer to: https://github.com/NLog/NLog/blob/master/src/NLog/Config/LoggingConfigurationFileLoader.cs#L101-L120

查看更多
劳资没心,怎么记你
6楼-- · 2019-08-20 02:27

You can add an extension method to your context class that gets you the required asset as a stream:

 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;
        }
    }
 }

And then in your activity context access it like:

var Asset= context.GetFromAssets("AssetName");

Note that this will return a System.IO.Stream.

Good luck

Revert in case of queries.

查看更多
登录 后发表回答