I have text files, I need to add a space at the 8th character of each line in the text file. Text files have 1000+ multiple rows

How would I conduct this?

Original file example:

123456789012345....
abcdefghijklmno....

New file:

12345678 9012345
abcdefgh ijklmno

Reading this article is helpful:

Add a character on each line of a string

Note: Length of text lines can be variable (not sure if it matters, one row can have 20 characters, next line may have 30 characters, etc. All text files are in folder: C:\TestFolder

Similar question:

Delete character at nth position for each line in a text file

1 Answers

2
S.Serpooshan On Best Solutions

You don't need to use Regular Expressions here. One simple way is to use File.ReadAllLines to read all lines and simply add your char at desired position as in following code:

var sb = new StringBuilder();
string path = @"E:\test\test.txt"; //input file
string path2 = @"E:\test\test2.txt"; //the output file, could be same as input path to overwrite
string charToInsert = " ";
string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
    sb.AppendLine(line.Length > 8 ? line.Substring(0, 8) + charToInsert + line.Substring(9) : line);
}
File.WriteAllText(path2, sb.ToString());

Here I use a different path for output for test purposes (don't overwrite the input)

EDIT:

The modified code to loop through all .txt files in a folder:

string path = @"C:\TestFolder";
string charToInsert = " ";
string[] allFiles = Directory.GetFiles(path, "*.txt", SearchOption.TopDirectoryOnly); //Directory.EnumerateFiles
foreach (string file in allFiles)
{
    var sb = new StringBuilder();
    string[] lines = File.ReadAllLines(file); //input file
    foreach (string line in lines)
    {
        sb.AppendLine(line.Length > 8 ? line.Substring(0, 8) + charToInsert + line.Substring(9) : line);
    }
    File.WriteAllText(file, sb.ToString()); //overwrite modified content
}