You could try the following
1. Create a class called
FixedLengthString
(for example).
In the class you have a constructor with a the length as a parameter.
Then you can implement an
explicit conversion operator[
^] (it works as an overload of the assignment operator) so it pads a string shorter than the fixed length and truncates a longer string or throws an error message.
You should also override the
ToString
method in order to trim the trailing space.
Implent a method
void GetString(string fileContent, int index)
that copies a sub-string from a specific index.
2. Create a container class that has a list of FixedLengthString,
List<FixedLengthString>
, as a member variable and a Serialize and Deserialize method.
In the serialize method you loop through your list and append the strings to a
StringBuilder
. Then write the content of the StringBuilder variable to the file.
In the Deserialize method you read the file into a string and then you loop through the list and use the
GetString
method.
Update the index with the length of the current list member for every iteration.
Don't forget to add error handling if the file content is to short etc.
This will save you a lot of hassle if the number of strings are variable or will be increased over time.