Search code examples
c#.netjson.net-assembly

Dynamically obtaining Json Filenames


I have a series of files in my program, which take user input and store them as a KeyValuePair some of them have names, most of them just have a numeric ID associated with them. This information needs to remain persistent across the application starting and stopping. I've tried several approaches but I can't get any of them to work quite right.

My approach was to simply have a Content folder, full of .json files I knew I could expect. When the program first launched, it reads the file using the Newtonsoft JSON Deserializer, and loads it into the appropriate place in memory as a List<KeyValuePair<int,string>. That all works fine, but getting the path to the File has proven exceedingly difficult.

I started with literals, but then realized I need to be able to have the program in any directory. So then I tried finding the absolute path of the file, given its relative name to the project. Still doesn't work because debugging and publish directories, as well as copy on compile stuff. As a minor issue, I also am annoyed that I still needed to use a string literal here.

SO, I resolved to make it a .resx file. This immediately failed, because you can't edit a .resx at runtime. So, referenced the external .json file from the .resx. The process of getting the URI or Path from the .resx proved excruciating if not impossible. I first tried

Assembly.GetExecutingAssembly().GetManifestResourceStream("MyJsonFile.Json") which I hoped would work but didn't.

So I had it print out String.Join(Assembly.GetExecutingAssembly().GetManifestResourceNames()) all I got out from the console wasMyNamespace.Properties.Resources.resources` and no indication of how to further extricate the location of any particular resource.

I even tried Assembly.GetExecutingAssembly().Location and couldn't do anything useful form there because it referred to my exe in the debug folder.

My last hope was an embeded content file, but I can't save those during the run time either. I can refer to the properly with URIs instead of literal strings, but I can't save them mid runtime, like I would need to in order to save on edit, or to even save from memory on close.

If anyone can give me clear information on how to extricate the URI or Path of a file in my solution without using literals, I would greatly appreciate it. Because I am getting nowhere with research I've done and the tools I have.


Solution

  • If you put it in your bin/debug folder, you do not need the path. You just need the names of the files.

    Otherwise put the path in the .config file and then read it from there like this:

    <appSettings>
        <add key="Path" value="PathToFiles"/>
    </appSettings>
    

    Then get the setting like this:

    using System.Configuration;
    string path = ConfigurationManager.AppSettings["Path"];
    

    Make sure to import