Correct non page class?

  • Thread starter Thread starter brett
  • Start date Start date
B

brett

I have several pages that need to use a method I've written that
streams in text file content. I added a CS file to my website and
named it Utilities. It has two static methods. One method reads in a
file. The other method passes a particular text file path. It is
similar to:

public static string BookList(System.Web.HttpServerUtility pServer){
{
return texturizeFileContent(@"content\fiction2005BookList.txt",
pServer).ToString();
}
}

public static StringBuilder texturizeFileContent(string pFilePath,
System.Web.HttpServerUtility pServer){

StreamReader sr = new StreamReader(pServer.MapPath(pFilePath));
//other code here }


In any ASPX page that needs to access this method, I do this:

lblBookList.Text = Utilities.BookList(Server);

I'm passing in a System.Web.HttpServerUtility object because I wasn't
sure how else to get a MapPath(). Any suggestions?

I'll add more static methods as more text files are added. The above
method works and keeps me from chasing down file paths, should they
ever change. Is this the correct way to allow multiple pages to access
a non page class?

Thanks,
Brett
 
You can use HttpContext.Current ...which'll be null for non-web requests so
you won't be able to re-use that class in a winform (for example)...not like
you can re-use it now anyways..

HttpContext context = HttpContext.Current;
if (context == null)
{
throw new Exception("Method cannot be used outside of web context");
}
using (StreamReader sr = new StreamReader(context.Server.MapPath(filePath))
{
...
}


notice how I also used using and fixed your variable naming ;)
(j/k...sorta...)

Karl
 
Back
Top