question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

UseJsonFile() throws System.IO.IOException

See original GitHub issue

Issue overview

If I understand this correctly, this library gives you an option not to only read, but also write new values to provided configuration (correct me if I’m wrong), so I decided to try out an example from the documentation using UseJsonFile(), but got System.IO.IOException when attempted to assign “New” value.

Code:

using Config.Net;

namespace MyApp
{
   class Program
   {
      static void Main(string[] args)
      {
         ISettings settings = new ConfigurationBuilder<ISettings>()
            .UseJsonFile("appsettings.json")
            .Build();

         Console.WriteLine(settings.Option);
         settings.Option = "New";
         Console.WriteLine(settings.Option);
         Console.ReadKey();
      }
   }

   public interface ISettings
   {
      public string Option { get; set; }
   }
}

appsettings.json that is in the same folder as executable:

{
   "Option": "Old"
}

What is causing the problem

The exception is being thrown in Config.Net.Json.Stores.JsonFileConfigStore.WriteJsonFile() line 165: File.Replace(tempPath, _pathName, backupPath);

I checked MSDN File.Replace method documentation and recreatd the example, everything was fine. Then i changed this example, so it looks like WriteJsonFile() method: original file is being created within the Temp folder by calling Path.GetTempFileName():

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string originalFilePath = @"D:\test1.xml";            
                string fileToReplace = @"D:\test2.xml";
                string backUpOfFileToReplace = fileToReplace + ".backup";

                // Create temporary file
                string tempPath = Path.GetTempFileName();
                string allText = File.ReadAllText(originalFilePath);
                byte[] data = Encoding.UTF8.GetBytes(allText);
                using (FileStream tempFile = File.Create(tempPath, 4096, FileOptions.WriteThrough))
                    tempFile.Write(data, 0, data.Length);

                // Replace the file.
                File.Replace(tempPath, fileToReplace, backUpOfFileToReplace, false);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}

As expected, System.IO.IOException was thrown. Every file does exist, so my only guess is that there’s something wrong with *.tmp files that get created within the Temp folder: it does really contain new values to overwrite, but probably File.Replace() method can’t do it with such temporary files. Also, if we create temporary file in some other directory, for say, project folder, then it works ok.

StackTrace

at System.IO.FileSystem.ReplaceFile(String sourceFullPath, String destFullPath, String destBackupFullPath, Boolean ignoreMetadataErrors)
at System.IO.File.Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName, Boolean ignoreMetadataErrors)
 at System.IO.File.Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName)
 at ConfigurationTests.Program.Main(String[] args) in D:\Visual Studio Stuff\repos\ConsoleTests\MyApp\Program.cs:line 22

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:7

github_iconTop GitHub Comments

1reaction
vgdhcommented, Aug 3, 2022

Thank you. On version 5.1.2 it works fine! 👍

0reactions
jeffward01commented, Jul 29, 2022

Why do you use .UseJsonFile(<string>)?

ISettings settings = new ConfigurationBuilder<ISettings>()
            .UseJsonFile("appsettings.json")
            .Build();

You should use: UseJsonConfig() as I mentioned earlier. It is the more updated method (I believe I am correct on this @aloneguid please correct me if i am wrong). and UseJsonConfig() expects a file with the name appsettings.json so you do not need to include appsettings.json

Change your method to this and it should work fine:

Settings settings = new ConfigurationBuilder<ISettings>()
            .UseJsonConfig().Build();
Read more comments on GitHub >

github_iconTop Results From Across the Web

System.IO.FileNotFoundException In ConfigurationBuilder ...
I checked and in the Directory.GetCurrentDirectory() the file appsettings.json is present. System.IO.FileNotFoundException HResult=0x80070002 ...
Read more >
Microsoft.Extension.Configuration.Json.AddJsonFile of an ...
Json.AddJsonFile of an JSon Array file fails with Error: Unsupported JSON ... It throws: Error: Unsupported JSON token 'Array' was found.
Read more >
Application configuration in .NET Core – Part 1
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Microsoft.Extensions.Configuration.
Read more >
Setting ASP.NET host address in .NET Core 2 - Bill Boga
If a second app. is run, this error is thrown: ... System.IO.IOException: Failed to bind to address http://127.0.0.1:5000: address already ...
Read more >
System.IO.IOException: The configured user limit (128) on ...
Hi... The following error occurred because of the code generated using Entity Developer. "System.IO.IOException: The configured user limit ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found