0

I have a json file I am trying to read via a StreamReader. The json is in the same directory as my code. However, any method for loading the file (GetFullPath(), GetDirectoryName(), etc) is always looking in the \bin\Debug\netcoreapp3.1 directory, where it obviously is not. I have tried all the different versions

I think that has more to do with an issue with netcoreapp than anything else. How do I get it to just load the file in the same directory?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Limey
  • 2,642
  • 6
  • 37
  • 62

2 Answers2

1

Option 1: Don't include a path at all. That will use the current directory, which by default is the directory of the executable file. I mention this for completeness, but it probably won't work, because your executable is not in the same folder as your code!

Option 2: Look for the file in Visual Studio's Solution Explorer. The properties for the file there will include an option to Copy to Output Directory that is probably currently set to Do not copy. You want this to be Copy always or Copy if newer. Then, when you build your project, it will place the file in the Debug or Release folder with your program.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • This was my big miss! Its been so long since I have had to do this, I forgot about copying to output. C# really needs to have better native support of json, that would be the best fix! – Limey Nov 08 '22 at 19:02
  • You have three different major options on NuGet for loading and writing JSON. – Joel Coehoorn Nov 08 '22 at 19:07
  • You have one you suggest? I ask, cause most of the json Schema validators out there still you streamReaders as part off all their examples. – Limey Nov 08 '22 at 19:17
1

When you build your project the compiled code is copied to the \bin\Debug\netcoreapp3.1 directory. The application than runs from there. So the 'problem' you are referring to is actually the expected behaviour.

You can either:

  • Manually copy the file to the build folder
  • Use a variable to refer to the correct folder location (this way you can change it easily if you want, you kan even put in in the settings file)
  • Configure your project to automatically copy the json file to the build folder see this question
Marc van Nieuwenhuijzen
  • 1,637
  • 1
  • 14
  • 22