问题
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);
}
回答1:
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.ReadAllText on every file path.
var dialog = new OpenFileDialog() { Multiselect = true,
Filter = "Data Sources (*.ini)|*.ini*|All Files|*.*" };
if (dialog.ShowDialog() != DialogResult.OK) return;
var paths = dialog.FileNames;
var fileContents = paths.ToDictionary(filePath => filePath, File.ReadAllText);
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.ReadAllText
on every one of them.
// same as first snippet without the last line
foreach (var filePath in paths)
{
fileContents.Add(filePath, File.ReadAllText(filePath));
}
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_settings
needs to be a string
).
var dialog = new OpenFileDialog{Filter = "Data Sources (*.ini)|*.ini*|All Files|*.*"};
if (dialog.ShowDialog() != DialogResult.OK) return;
m_settings = File.ReadAllText(dialog.FileName);
回答2:
if you can add description of what are you trying to accomplish it would help.
just the same, I would use to store/read settings by using the settings class
here is a link to how to use it: write user settings
I used in the past xml to parse a settings file, i find it much easier than reading ini in a sequential manner.
Hope it helps
来源:https://stackoverflow.com/questions/11926708/c-storing-the-content-of-an-ini-file-as-string-or-dictionary-instead-of-file-n