Question

I am developing an Add-In (in C#) for Visual Studio 2012 and I am trying to use NLog to log information from the Add-In code to a local log file (e.g. in the same local directory that the Add-In is being loaded from). Nothing was being logged and then when I debugged things some more it seems that I just do not have write access to the local file system from inside the Add-In code. Simply trying to open a local file and write a line to it throws a System.UnauthorizedAccessException:

[System.UnauthorizedAccessException] = {"Access to the path 'C:\\Program Files (x86)\\Microsoft Visual Studio 11.0\\Common7\\IDE\\test.txt' is denied."}

Is this just a basic limitation for Add-Ins? Does VS just not allow write access to the local file system?

Thanks for any insight you can offer

Alan

Was it helpful?

Solution

After digging around in the NLog source code I finally figured out what was going on here.

The real problem was that I was putting the NLog.config file in the wrong place and so NLog was not finding it. I was putting it in the Add-In directory with the .AddIn file and the binaries. Rather than throwing some kind of exception NLog was just silently disabling logging. This is perfectly reasonable behavior in hindsight since it's legitimate for logging to be just disabled if the config file is not present. Anyway, no logs were getting written and my first thought was that it might be a permissions issue. I then just tried to create a file (test.log) and write to it in my Add-In code and then saw the exception above which just reinforced my (incorrect) suspicion that there's some security model that prevents Add-Ins from writing to the file system.

So, we need to be mindful of directories:

  • The Add-in Directory: This is where the .AddIn file and related binaries will live. This is where Visual Studio will look for Add-ins and load them from.

  • The default directory for Visual Studio: Remember that it's devenv.exe that owns the process, not the Add-in. So the default directory will be where devenv.exe lives not where the Add-in lives. Also note that this directory is write protected for non-Admin users. This is where NLog will look for the NLog.config file!

  • The path to the logfile target in the NLog.config file: This needs to be a writeable location. Just specifying a file (e.g. test.log) in the target will represent a file in the default working dir for Visual Studio which, as we noted above, is not a writeable location.

So, in order to make things work I had to:

  • Put the NLog.config file in C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE. I needed to do this as Admin.
  • Specify a full (writeable) path for the logfile in NLog.config
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top