Ad

How To Read Content In A Line Of A File.txt

- 1 answer

I have a line like this:

114765 * 3 * 659300 * 01 * 17/01/2013 * * 1 * Chuck Norris * Chuck Norris Jr* Owner * 1 * 28/04/1983 * Conjuge * * * 16/1/2013 * 1 * Quadro Social *

As you can see, the content/fields are separted by * they are fields like matriculation, name, dependent's name, category etc... I'd like to know how could I ´read` it, one by one ?

Also I need to reorder this and write a new file.txt, with these content reordered and without the *... I'm totally lost !
After I read it and remove the * I need to replace them like \field\: \114765\\3\\659300\\01\\17/01/2013\\1\\Chuck Norris\ I tried substring() and StreamWriterStreamReaderReadLine but I couldn't do what I need ;\

Ad

Answer

Use String.Split to get a string[] of the columns. You can use String.Join to join all parts together to a new string and File.WriteAlltext or File.WriteAllLines to write it back.

After I read it and remove the * I need to replace them like \field\:

So you need to replace the * with \:

string[] parts = line.Split(new[] { '*' }, StringSplitOptions.RemoveEmptyEntries);
string newLine = string.Join("", parts.Select(p => string.Format("\\{0}\\", p.Trim())));
File.WriteAllText(filePath, newLine);

Demo

Result:

\114765\\3\\659300\\01\\17/01/2013\\\\1\\Chuck Norris\\Chuck Norris Jr\\Owner\\1\\28/04/1983\\Conjuge\\\\\\16/1/2013\\1\\Quadro Social\\\

Update:

If you want to ignore parts that are empty(caused by two consecutive * * in the string), then you can use this code:

var nonEmptyParts = parts
    .Where(p => !string.IsNullOrWhiteSpace(p))
    .Select(p => string.Format("\\{0}\\", p.Trim()));
string newLine = string.Join("", nonEmptyParts);

That'll result in:

\114765\\3\\659300\\01\\17/01/2013\\1\\Chuck Norris\\Chuck Norris Jr\\Owner\\1\\28/04/1983\\Conjuge\\16/1/2013\\1\\Quadro Social\

I'd want to ignore the first 2 strings of the array, you know just remove it, throw it away

That is Enumerable.Skip:

var nonEmptyParts = parts.Skip(2)
    .Where(p => !string.IsNullOrWhiteSpace(p))
    .Select(p => string.Format("\\{0}\\", p.Trim()));
Ad
source: stackoverflow.com
Ad