Is there a way to store the content of a file as string or as a dictionary instead of just its file path/name?
Below is the method that I am currently using for getting the file path from a Windows Form. Is there a way to adapt it or should I start from scratch? I am loading .ini files which is only text. LINQ seems to be one route but I am not familiar with it.
public void ShowSettingsGui()
{
System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
ofd.Multiselect = false;
ofd.Filter = "Data Sources (*.ini)|*.ini*|All Files|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
string[] filePath = ofd.FileNames;
}
m_settings = Path.GetDirectoryName(ofd.FileName);
}
LINQ is indeed a nice way to do it: We simply convert the paths to a dictionary (where they become the keys). The values are determined by calling
File.ReadAllTexton every file path.To help you understand what’s going one here, take a look at the (roughly equivalent) non-LINQ version. Here, we explicitly iterate over the FileNames and add them as keys to our dictionary while again calling
File.ReadAllTexton every one of them.Set a breakpoint to the last line of each snippet, run them and take a look at the contents of the dictionary to determine the result.
EDIT: It wasn’t clear in the question, but it seems you’re only interested in a single file name. That means you don’t need LINQ at all (
m_settingsneeds to be astring).