So when I am using the WinForms GUI the file is found, but when I am using the MVC website, the project can't find it.
To answer the reason why you are observing the difference is called the current working directory. By default, when VS.NET launches Windows apps or consoles, the working directory is to the relevant bin directory.
All relative file operations, such as File.ReadAllLines("the.file")
, will concatenate to an absolute file path as per below.
Path.Combine(Directory.GetCurrentDirectory(), "the.file");
ASP.NET's working directory would not correlate to the root of your web application.
Where should I place the file in the MVC proejct?
As suggested by @dariogriffo, it should be placed in the ~/App_Data/*
directory.
I have a solution which has two presentation layers. One is using ASP.NET MVC, the other WinForms. Both projects depend on a third projecs which does some business logic and is a class library.
So now you are in a little bit of a pickle over here with your current implementation and the way the current working directory is implemented. Without delving into too much detail, I suggest that the code figures out how to load the file indirectly such as passing in an interface with a contract such as the following.
public interface IDictionaryRepository {
IEnumerable<string> LoadAllWords();
}
With the above, you can change your business logic to the following
public static string[] Dictionary()
{
if (_dictionary == null)
{
_dictionary = _dictionaryRepository.LoadAllWords().ToArray();
}
return _dictionary;
}
The benefit of the above abstraction is that you may then easily substitute the file finding logic as per the other suggestions easily, and maybe migrate your dictionary to be hosted in a database somewhere.