Recursive script inclusion with REQUIRE (C#)

This is the C# version of the script I posted earlier. It's also available as a VB.net version.

using System;
using System.Collections;
using System.IO;
using System.Web;

public partial class javascript : System.Web.UI.Page
{
	private Stack files;

	protected void Page_Load(object sender, EventArgs e)
    {
		files = new Stack();
		Response.ContentType = "application/x-javascript";
		Response.Write(GetFile("js/Contacts.js"));
	}

	private string GetFile(string path)
	{
		string result = "";
		string filespec = HttpContext.Current.Request.PhysicalApplicationPath +
						 path.Replace("/", "\\");

		filespec = Path.GetFullPath(filespec);

		//if the file is already loaded, then exit
		if(files.Contains(filespec))
			return "";

		//add this file to the loaded list
		files.Push(filespec);

		//load the file
		string s = "";
		bool b = false;
		try {
			StreamReader sr = File.OpenText(filespec);
			do {
				b = true;
				s = sr.ReadLine() + "\n";
				if(s.IndexOf("//LIBRARY:") == 0)
					b = false;

				if(s.IndexOf("//REQUIRES:") == 0) {
					b = false;
					s = s.Replace("//REQUIRES:", "").Trim();
					result = result + GetFile(".." + s);
					s = "";
				}
				result = result + s;
			} while (sr.Peek() != -1 && !b);
			result = result + sr.ReadToEnd() + "\n";
			sr.Close();
		} catch {
			result = "\n/* Error loading file: " + filespec + " */\n"
		}
		return result;
    }
}
comments powered by Disqus