I need a sensible way to draw arbitrary text files into a C# program, and produce an arbitrary anonymous type object, or perhaps a composite dictionary of some sort.
I have a representative text file that looks like this:
adapter 1: LPe11002
Factory IEEE: 10000000 C97A83FC
Non-Volatile WWPN: 10000000 C93D6A8A , WWNN: 20000000 C93D6A8A
adapter 2: LPe11002
Factory IEEE: 10000000 C97A83FD
Non-Volatile WWPN: 10000000 C93D6A8B , WWNN: 20000000 C93D6A8B
Is there a way to get this information into an anonymous type object or some similar structure?
The final anonymous type might look something like this, if it were composed in C# by hand:
new
{
adapter1 = new
{
FactoryIEEE = "10000000 C97A83FC",
Non-VolatileWWPN = "10000000 C93D6A8A",
WWNN = "20000000 C93D6A8A"
}
adapter2 = new
{
FactoryIEEE = "10000000 C97A83FD",
Non-VolatileWWPN = "10000000 C93D6A8B",
WWNN = "20000000 C93D6A8B"
}
}
Note that, as the text file's content is arbitrary (i.e. the keys could be anything), a specialized solution (e.g. that looks for names like "FactoryIEEE") won't work. However, the structure of the file will always be the same (i.e. indentation for groups, colons and commas as delimiters, etc).
Or maybe I'm going about this the wrong way, and you ha开发者_开发知识库ve a better idea?
You're going about this the wrong way. Your "anonymous type object" data is hard to construct and hard to use. To construct it, you'd have to use reflection trickery. And for what?
Consider a PrintReport function. This function would not get any simpler because of the ATO usage. Far from it, it'd get more complicated and slow, having to use reflection itself to iterate over the keys. Your solution might have made sense if there was a small, fixed number of possible keys. Then usage syntax such as "obj.FactoryIEEE" might have been preferred.
The way I'd go about this is with a List<Dictionary<string, string>>
, or, say a List<AdapterRecord>
where AdapterRecord is
class AdapterRecord
{
public string Name { get; set; }
public Dictionary<string, string> Parameters { get; set; }
}
Check out this 2-part article. It parses XML files in a fluent way. It can be adapted to parse your text files I think.
- Fluent XML Parsing Using C#'s Dynamic Type Part 1
- Fluent XML Parsing Using C#'s Dynamic Type Part 2
It uses C# 4 dynamic typing to do what you want.
It looks like there's no way to do this even in C# 4.
Besides, thinking about it if you don't know what the keys will be then any sort of strongly typed access would be tough, and a simple split + insertion into dictionary/list/etc. would make more sense.
While I don't love them, perhaps a DataTable
would serve...
精彩评论