Correct non page class?

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
 
K

Karl Seguin

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top