Heike
Heike

Reputation: 148

Append string in a specific place of a text file

I have hundreds of files in a directory. Many of the text files have the Code Column values as blank and i need to iterate over all the text files and fill it. I am able to write the code to add the code value in a new line, but i am not able to write it under code column. String value is: "STRINGTOENTER". I only want it be entered in the 1st line after the header. The last line should be left alone

 
Id    Code    File_Number   Suffix  Check_Number    Check_Date
047 7699 01 99999 11/11/2012 1 -6.15
Below is my code snippets that add the value at a newline. I think I need to do a regular expression or a tab delimited type solution here.

 public static void AddAStringtoAllTextFiles()
    {
        try
        {
            string path = @"C:\Users\ur\Desktop\TestFiles\";
            string[] fileEntries = Directory.GetFiles(path);
            for (int i = 0; i < fileEntries.Length; i++)
            {

                File.AppendAllText(fileEntries[i], "STRINGTOENTER" + Environment.NewLine);
           }
        }

        catch (Exception e)
        {
            throw e;
        }
    }

Upvotes: 0

Views: 707

Answers (3)

Heike
Heike

Reputation: 148

I want to show my desired solution based on your input. Amazing how a simple piece of code can contribute to solving a larger and a complex problem. Thanks again!

     public static void AddClientCodetoAllTextFiles(string update_batch_with_clientcode, string batchfilepathtobeupdated)
    {      

        try
        {
            var fileEntries = Directory.GetFiles(@batchfilepathtobeupdated.Trim());

            foreach (var entry in fileEntries)
            {
                var lines = File.ReadAllLines(entry);

                if (lines.Length > 1)
                {
                    for (int i = 1; i < lines.Length - 1; i++)
                    {
                        var split = lines[i].Split('\t');
                        split[1] = update_batch_with_clientcode.Trim();
                        lines[i] = string.Join("\t", split);

                        File.WriteAllLines(entry, lines);
                    }

                }

            }

        }

        catch (Exception e)
        {
            throw e;
        }
    }

Upvotes: 0

Ajeet Kumar
Ajeet Kumar

Reputation: 729

EDITED please try this with the assumption that its space(s) delimited.

its working on my VS2017 and kindly add the using statement on the top as below .

 using System.Text.RegularExpressions

    public static void AddAStringtoAllTextFiles()
    {
        try
        {
            string path = @"C:\Users\ur\Desktop\TestFiles\";
            var fileEntries = Directory.GetFiles(path);
            int indexPosition2InsertData=1;
            foreach (var entry in fileEntries)
            {
                var lines = File.ReadAllLines(entry);
                for (var index = 1; index < lines.Length; index++) //starting  from first row, leaving the header
                {
                    var split= Regex.Split(lines[index].Trim(), @"\s{1,}"); //reading the line with space(s)
                    if(split.Length==5) //edited //checking if the row is not blank
                    {
                        var list = split.ToList(); //convert to list to insert
                        list.Insert(indexPosition2InsertData, "STRINGTOENTER"); //inserting at the index 1
                        lines[index] = string.Join("\t", list);
                    }
                }
                File.WriteAllLines(entry, lines);
            }
        }

        catch (Exception e)
        {
            throw e;
        }
    }

I am getting this after running the code.

Id    Code    File_Number   Suffix  Check_Number    Check_Date

047 STRINGTOENTER   7699    01  99999   11/11/2012
1   -6.15

Please let me know if this helps.

Upvotes: 1

TheGeneral
TheGeneral

Reputation: 81503

Assuming each file has the right tab delimitation (and that's a big assumption given the question quality)

// Get the files
var fileEntries = Directory.GetFiles(path);

// iterate through each file name
foreach (var entry in fileEntries)
{

  // Load the File into the lines array
  var lines = File.ReadAllLines(entry);

  // Iterate over each line
  if(lines.Length >1)
  {
     // Split the lines by tab
     var split = lines[1].Split('\t');
     // your code should be at array index 1
     split[1] = "STRINGTOENTER";
     // write the whole line back
     lines[1] = string.Join("\t", split);

     // write the file
     File.WriteAllLines(entry, lines);
  }

}

Note : you should probably do this with a CSV parser, this was only for academic purposes and totally untested

Upvotes: 0

Related Questions