I had a text file log.txt and want to replace lines 3,6,9,12....... with "0". Suppose I have x no of lines in file "C:/log.txt", that is written using C#, and want to edit line no's that are divisible by 3 i.e 3,6,9,12,15.....,x. Any Code?
Hi there, Since you've written the file in C# I assume you already know how to open and write the actual text file. To find the row divisable by 3 when you loop through the lines in the file, use the modulus operator: %.
I had written the file using C# but unable to edit the specific lines. Could you provide me the full code? Plz
Here int "line count"; //enter number of lines in txt file StreamWriter sw = new StreamWriter("log.txt", true); for (int i = 0; i < line count; i++) { if (line count % 3 == 0) sw.WriteLine("0"); } sw.Flush(); sw.Close(); Code (markup):
This will work fine. It reads the contents of your file into an Arraylist, then writes it back out, missing out every 3rd row ArrayList al = new ArrayList(); string filename = @"c:\log.txt"; using (StreamReader sr = new StreamReader(filename)) { string line; while ((line = sr.ReadLine()) != null) { al.Add(line); } sr.Close(); } using (StreamWriter sw = new StreamWriter(filename)) { int lineCount = 1; foreach (String str in al) { if (lineCount % 3 == 0) sw.WriteLine("0"); else sw.WriteLine(str); ++lineCount; } sw.Close(); } Code (markup):