I have multiple text files in folder. I need to delete character at the 8th character of each line in the text files. Text files have 100+ multiple rows
How would I conduct this?
Original file example:
123456789012345....
abcdefghijklmno....
New file:
12345679012345
abcdefgijklmno
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:
Insert character at nth position for each line in a text file
You can use File.ReadAllLines()
and string.Substring()
methods as follwing:
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, 7) + line.Substring(8) : line);
}
File.WriteAllText(file, sb.ToString()); //overwrite modified content
}
line.Substring(0, 7)
means first 7 characters (char #0 to #6 with length of 7).
line.Substring(8)
means from 9'th character to end (char #8 to end).
Note that char positions are zero-indexed!