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?
I think both ways are perfectly valid.
Server.MapPathis 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:
When I unit-test, I just mock it to returns something meaningful for the tests.