Search code examples
c#.netpath

Could not find a part of the path, when i create an instance of another application's class


I have two applications:

  • CommServer
  • CacheProxy

CacheProxy stores some data cache in json files and synchronizes them. These files are located in ..\CacheProxy\bin\Debug\net8.0\cache\.

But when CommServer creates an instance of the class that is in CacheProxy. Then the absolute path becomes ..\CommServer\bin\Debug\net8.0\cache\ and therefore it does not find this file.

Is it possible to make it so that when CommServer uses the class of the running application CacheProxy, then the path is also to ..\CacheProxy\bin\Debug\net8.0\cache\

what is the best way to do it? store json files relative to all applications, or store the path in appsettings.json


Solution

  • You should never write files into the current working directory of the application, because if you do that, then:

    • you run into situations like the one you are experiencing
    • on production, the current working directory will be under C:\Program Files and your application might not even have write permissions to it.

    Redirecting your "bin" directory to a common location is not a solution: it will initially seem to work while debugging, but as soon as you move to production it will miserably fail, due to insufficient permissions to write under C:\Program Files.

    Instead, you have a couple of options:

    1. Write files into some well-known common directory. For example, this could be "My Documents" (see Stack Overflow: How can I get the location of a user's Documents directory?) or "Local AppData" (see Stack Overflow: How do I get %LocalAppData% in c#?)

    2. Make each of your apps accept a command-line argument specifying where shared files are located, and pass $(MSBuildProjectDir)\.. to both. This way, they will be sharing files in the directory which is one level above the project directories, which is usually the solution directory.