How to read flat file schema using Reflection in C #
How to read a schema of a flat file using Reflection in C # A short overview I have: there is some server that stores data as flat files and I have to transfer data from SQL Server to these flat files. To do this, I need to know their scheme. I have no idea about this, any help would be great.
It's hard to know where to start this question because it looks like reflection is unlikely to be helpful, and yet you indicated that it should appear in the solution! :)
As a result, this answer is mostly a guess and is likely to evolve as you uncover more information. It is perfectly; you cannot get the answer (42) until you know what the question is.
There is no single definition of what a flat file is. You probably want a function that parses the "records" in the file. The usual approach is to open the file in a hex editor and infer the format from a few sample entries. Look for clues about the shape of the repeating pattern. Seems like each "record" consists of several "fields"? Do they come out in a specific order each time, or is each field prefixed with a name or number to indicate what it means? It looks like plain text i.e. Can you open it in Notepad without losing important information?
Declare a class to represent the record:
public class FlatFileRecord
{
public string FirstName { get; set; }
public string LastName { get; set; }
// etc.
}
Then write a function that reads from the stream and outputs the entries:
public static IEnumerable<FlatFileRecord> ParseFlatFile(StreamReader stream)
{
// etc.
It would make sense to use a StreamReader if the file is "plain text" (that is, it has carriage return / line feed characters that are used in some significant way to delimit records or fields).
Suppose each record is a line of plain text (in other words, each record is separated by a special line ending sequence). Within this line, there are several fields that are somehow delimited by other special characters. Your parser can be structured like a loop:
string line;
while ((line = r.ReadLine()) != null)
yield return new FlatFileRecord(line);
This breaks the problem down into two levels. The outer layer traverses the lines one at a time, each of which makes one record. Then there is the inner layer, which I imagined when creating the FlatFileRecord constructor. Pass in a string and it is filled with field values ββthat it knows how to extract from that string. So now you need to write the FlatFileRecord constructor.
source to share