Mike19
Mike19

Reputation: 95

Append text (string values) to each line to a txt-file

Figures 1 and 2 show an example for a txt file. The number of string values are sometimes different. How can I append text (string value X ) to fill each line , so that each line has the same number of strings (see figure 3) Each line of a txt file has 7 string comma seperated values). Can anyone help me please?

Here is my code so far (in C#):

File.WriteAllLines(path, File.ReadAllLines(path).Select(s => $"{s}, X"));

enter image description here

Upvotes: 2

Views: 1200

Answers (1)

Mahmoud Ramadan
Mahmoud Ramadan

Reputation: 672

I hope that helps you, and I assume that you want to read a source file and append the text to the destination file, Look at the result

using System;
using System.IO;
using System.Linq;

namespace Stack_Overflow {
    class Program {
        static void Main(string[] args) {
            StreamReader sr = new StreamReader("source.txt"); // read the source text file
            string appendedText = sr.ReadLine();   // get the first line
            sr.Close(); // close the stream

            string[] lines = File.ReadAllLines("dest.txt"); // read the all lines of the destination text file to know the maximum line length
            int maximumLineLength = lines.OrderByDescending(a => a.Length).First().ToString().Split(',').Length;  // get maximum line length using LINQ

            foreach (var line in lines) {
                appendTheText(line, (maximumLineLength - line.Split(',').Length) + appendedText.Length, appendedText);  // the second parameter here is the number of iterations that must we loop through each line
            }

            Console.WriteLine("Task finished successfully!");
            Console.ReadLine();
        }

        static void appendTheText(string line, int iterationCount, string appendedText) {
            StreamWriter sw = new StreamWriter("dest1.txt", true);
            sw.Write(line);
            for (int i = 0; i < iterationCount; i++) {
                sw.Write($",{appendedText}");
            }
            sw.WriteLine();
            sw.Close();
        }
    }
}

NOTE that you must exclude the comma when you want to get the length of the line because we have a line that has odd commas and another has even commas So when we try to append our text to the line that has odd commas, we will find that line has an extra value So I split the text with Comma

Upvotes: 3

Related Questions