P.Brian.Mackey
P.Brian.Mackey

Reputation: 44275

Is there any reason to use Server.MapPath() to reference a file store?

I have seen several developers perform:

string fileStore = Server.MapPath(@"~\someDirectory");
File.Create(fileStore + "someFileName.xxx");

I find that this makes unit testing difficult. Since I test with MSTest, there's no HTTP context, so this code just flat out fails.

Instead, I store my file paths in web.config.

string fileStore = ConfigurationManager.AppSettings["fileStore"];

This works with unit tests. Why do developers use Server.MapPath() in this way? Are there some benefits I'm unaware of?

Upvotes: 3

Views: 496

Answers (3)

CheckRaise
CheckRaise

Reputation: 550

When you don't control your own hosting environment it may be impossible to know the full path. You have to rely on Server.MapPath() in that aspect. Storing it in AppSettings assumes you know the full path up front.

Upvotes: 1

Robert
Robert

Reputation: 8767

Server.MapPath() maps the specified relative or virtual path to the corresponding physical directory on the server. This will always be relative to the file that contains the code so there is no real room for error. You can always use an external file to store the "global variable", such as your web.config file in this case.

Either solution is viable, and there are likely plenty more out there. I think the biggest thing in this case would be which one better suits your needs.

Upvotes: 1

Dan Abramov
Dan Abramov

Reputation: 268215

I think both ways are perfectly valid.

Server.MapPath is more easily readable but is harder to test.
Keep in mind, though, that unit testing wasn't supported by ASP .NET at all (before the MVC thing).

Personally, I tend to create a directory service that gives me the paths:

public interface IDirectoryService {
    string MapPath(string relative);
}

public DirectoryService : IDirectoryService {
    public string MapPath(string relative)
    {
        return Server.MapPath(relative);
    }
}

When I unit-test, I just mock it to returns something meaningful for the tests.

Upvotes: 3

Related Questions