Search code examples
c#asp.net.netfilestream

Alternative to FileStream in C# .NET


In an Visual Studio environment, Project A (ASP.NET) references Project B (C#) in my solution like this:

Solution
├─Project B
│ ├─data.txt
│ └─process.cs  (a class BB with static initialization new FileStream("data.txt"))
└ Project A (referencces Project B)
  ├─bin
  │ └─data.txt (copied from project B each time project B changes)
  └─Controllers
    └─mycontroller.cs (references the class BB)

The problem is that when I run the application, the working directory is C:\Program Files (x86)\IIS Express\, so that data.txt cannot be read from the compiled version of process.cs which is in bin.

For the moment, to solve the problem, I manually copied data.txt to this folder, but this solution is not viable. Note that changes to B must be coherent with other projects depending on B, which are not all ASP.NET project.

What changes should I make so that data.txt is accessible from my project without relying on me to copy the data.txt file to the IIS Express directory?

I would like to port my program to Azure Online and I cannot rely on this method. Thank you for your help.

Other linked answers:

  • This answer is ASP.NET - specific, I cannot add server.MapPath because the project does not know about it.
  • This answer references project paths, but does not give me an hint about how to modify them.

Solution

  • "Note that changes to B must be coherent with other projects depending on B, which are not all ASP.NET project"

    Not sure what coherent would mean to you in context of other projects which depend on project B... But following options come to mind -

    1. Embed data.txt as a resource in the assembly generated for project B. Project B, can then read the file as a resource (This assumes, file contents do not need to be modified after the build) See ResourceManager class for handling resources embedded in assemblies. http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager(v=vs.110).aspx

    2. If it works for all clients of Project B, scan sub-directories for the file.. This is more hackish.. but really depends on the scenarios for project B.