App_Code folder in Web Application Project using Visual Studio 2012

2.8k Views Asked by At

I know the feature of App_Code folder in website project, however if I want to add this folder in Web Application Project the purpose remains same, i.e I want to put some un-compiled code in my application.

I am aware of "Build Action" option in file properties, if we set it to "Compile", Visual Studio will compile the code (that is in App_Code folder) so the purpose fails. But if I keep "Build Action" to "Content" (it make sense) then I can't access classes in this folder from any other part of the application.

How can I access this code from outside of App_Code folder if I keep files "Build Action" to "Content"?

2

There are 2 best solutions below

0
On

I don'T think it's standard.. Depending on your need, you can use .cs (assuming C#) and build action compile without creating a dll. The first request to the web server is gonna compile the website for you.

If you don't want the webserver to recompile the website everytime you change a file in the app_code, you're gonna have to use a scripting approach (you can refer to https://stackoverflow.com/.../what-is-the-best-scripting-language-to-embed-in-a-c-sharp-desktop-application). There are plenty of ressources about scripting, so I won't give example here.

2
On

You can access any content file in your application by reflecting on the assembly and getting the data that way. I usually use a tool like reflector from redgate to see the file and how it is named. Then, I use code like the following to actually read the file into a string.

Here is the basic code copied from another answer.

How to read embedded resource text file

var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyCompany.MyProduct.MyFile.txt";

using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
  string result = reader.ReadToEnd();
}