Search code examples
c#asp.netapp-code

How to access App_Code/file.cs from a aspx file?


I have the following file: App_code/utility.cs. This file needs to be accessed via a aspx file. In my aspx file I have the following <%@ Import Namespace ="../App_Code/Utility.cs" %>. When I try to build it I get the following error: Identifier expected. How do I access App_code/file.cs from a aspx file?

a small sample of the Utility.cs file:

public class Utility
 {
  public static string EncryptString(string fieldValue, string IV = "")
   {
      //code in here

    }
 }

this is what the start of the aspx file look like:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="file.aspx.cs" Inherits="file" EnableEventValidation="false" EnableViewState="true" %>

<%@ Import Namespace ="../App_Code/Utility.cs" %>

<!DOCTYPE html>

Solution

  • If you do not use namespace then direct call it on aspx page - like that.

    <%=Utility.EncryptString("theEncodedString") %>
    

    if you have namespace eg, if you have

    namespace myNameSpace
    {
      public class Utility
      {
         public static string EncryptString(string fieldValue, string IV = "")
         {
            //code in here
         }
       }
    }
    

    then you can declare it on the page

    <%@ Import Namespace ="myNameSpace" %>
    

    or direct use it to locate you class as

    <%=myNameSpace.Utility.EncryptString("theEncodedString") %>
    

    The files on App_Code compile as a dll library - you then use their class by including their namespace (and not by reference the file) - for asp.net the file is not exist, the compiled version of it as a dll exist.