1

How can I read a text file in line by line and assign :sometext: lines to a dictionary's keys and next to :somtext: lines to a dictionary's values? For example, how could I make the below new line delimited list:

my text file:

:II: Own BIC / TID
COBADEFFDOC BIC could not be resolved
:IO: Correspondents BIC / TID
abc BIC identified as:
xyz AG,THE,pqe BRANCH
zxc

output:

dictionary key ->  :II:
dictionary value ->  Own BIC / TID COBADEFFDOC BIC could not be resolved


dictionary key ->  :IO:
dictionary value ->  Correspondents BIC / TID
                             abc BIC identified as:
                              xyz AG,THE,pqe BRANCH
                              zxc

Thanks in advance.

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Krejivikas
  • 11
  • 2
  • Are you sure this is c# ?. Anyway, if you want to read the contents of a file in c#, you could use "Stream". You can read about it here. http://stackoverflow.com/questions/1404303/c-sharp-using-streams – Alf Moh Mar 02 '17 at 05:46
  • yes reading from text file.. using StreamReader – Krejivikas Mar 02 '17 at 05:48
  • `string[] Array = Regex.Split(TextContext, @":[a-zA-Z0-9]*[a-zA-Z0-9]:")` – Frank Myat Thu Mar 02 '17 at 06:16
  • 1
    See http://ideone.com/KwBlBF if you want to do it with a regex, just read the whole file into the memory. Note it will never be a good idea to use this approach for files of arbitrary length, only for smaller text files. – Wiktor Stribiżew Mar 02 '17 at 07:29

1 Answers1

1

I have tried it and almost working fine ...like this...

string[] allLines = File.ReadAllLines(@"E:\stackfiletext.txt");

Dictionary<string, string> dictionary = new Dictionary<string, string>();
int pFrom = 0;
int pTo = 0;
string result = "";
string keyValue = "";
bool firstIterataion = true;

for (int i = 0; i < allLines.Length; i++)
{
  if (allLines[i] != null)
  {
    string line = allLines[i];
    if (allLines[i].Contains(":") & allLines[i].Count(x => x == ':') > 1)
    {
       if (!firstIterataion)
       {
          dictionary.Add(":" + result + ":", keyValue);
          keyValue = string.Empty;
       }
       pFrom = allLines[i].IndexOf(":") + ":".Length;
       pTo = allLines[i].LastIndexOf(":");
       result = allLines[i].Substring(pFrom, pTo - pFrom);
    }
    else if (!(allLines[i].Contains(":") & allLines[i].Count(x => x == ':') > 1))
    {
       keyValue += line;
    }
    firstIterataion = false;
   }
 }
if (!firstIterataion)
{
   dictionary.Add(":" + result + ":", keyValue);
   keyValue = string.Empty;
}
J.SMTBCJ15
  • 471
  • 6
  • 20