Hello Guys, My job is to process the text files. following are the steps that i have to do.
1: To combine multiple text files into one text file
2: Add filename (but without extension) in the beginning of each text file.
3: and Finally, index the contents of the file by 1,2,3 i.e., if the contents of the text file are 378456 354789 564876
then index it with 1:378456 2:354789 3:564876 4:56879 ......so on

I have written the following code, which is combining the multiple text files into one file and also adds the file name without extension...but i am not able to index its contents. Please help me out....
Regards

static void Main(string[] args)
        {

            string[] files = Directory.GetFiles(@"F:\kkj\", "*.txt", SearchOption.AllDirectories);
        
            StringBuilder strFile = new StringBuilder();

            foreach (string file in files)
            {
                using (StreamReader sr = new StreamReader(file))
                {
               
                    string s = Path.ChangeExtension(file, null);
                    strFile.AppendFormat(s.Substring(s.LastIndexOf(@"\") + 1) + " ");
                    strFile.Append(sr.ReadToEnd());
                }

            }

            using (StreamWriter outfile = new StreamWriter(@"F:\kkj\" + @"\FinalOutputFile.txt"))
            {
                outfile.Write(strFile.ToString());
            }
        }

Dani AI

Generated

Nice start, , and ’s split-and-reassemble hint is right on. One improvement: avoid ReadToEnd+a giant StringBuilder. If you have lots of files, stream lines and write as you go. Also decide whether the index resets per file (your sample does) or stays global. The snippet below is memory‑friendly, writes the filename (no extension) first, handles any whitespace, and lets you switch : to ; easily.

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

class Program
{
    static void Main()
    {
        var root = @"F:\kkj";
        var output = Path.Combine(root, "FinalOutputFile.txt");
        var files = Directory.EnumerateFiles(root, "*.txt", SearchOption.AllDirectories)
                             .OrderBy(p => p, StringComparer.OrdinalIgnoreCase);

        const char sep = ':'; // change to ';' if you really meant semicolon

        using (var writer = new StreamWriter(output, false, Encoding.UTF8))
        {
            foreach (var path in files)
            {
                var name = Path.GetFileNameWithoutExtension(path);
                writer.Write(name + " ");

                int index = 1; // reset per file; move this outside the foreach to make indexing global
                foreach (var line in File.ReadLines(path))
                {
                    var tokens = line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var t in tokens)
                    {
                        writer.Write(index.ToString());
                        writer.Write(sep);
                        writer.Write(t);
                        writer.Write(' ');
                        index++;
                    }
                }
                writer.WriteLine();
            }
        }
    }
}

Tips:

  • Sorting files makes output deterministic.
  • Split((char[])null, RemoveEmptyEntries) splits on any whitespace, so multiple spaces/newlines are fine.
  • For very noisy input, replace the split with a regex for numbers only (e.g., \d+).
  • Wrap the per-file loop in try/catch if you might hit locked or unreadable files.

Recommended Answers

All 5 Replies

Did you make a counter that counts where it found the data?

Yes, I tried but failed to use counter according to my scenario.

Again, I want to give an example to make it more clear.
the contents of the text file (file1.txt)are numeric values separated by white space, i.e.,
file1.txt
2365 6598 8745 5648
5421 5784 9657 4562

Now i want to put counter to index every content of this text file by 1,2,3....
Example:

1:2365 2:6598 3:8745 4:5648
5:5421 6:5784 7:9657 8:4562

There should be a semicolon in between them

So, without the file processing, think about this:
Each row will need the counter attached multiple times.
Each line will need to be split, then modified, then re-assembled:

using System;
using System.Collections.Generic;

namespace DW_407604_CS_CON
{
   class Program
   {
      static void Main(string[] args)
      {
         string[] arr_str =
         { //pretend this came from the file into an array
            "2365 6598 8745 5648",
            "5421 5784 9657 4562"
         };

         int iCounter = 0;
         
         foreach (string s in arr_str)
         {
            List<string> lst_strStack = new List<string>();
            
            string[] arr_strInternal = s.Split(" ".ToCharArray(),
               StringSplitOptions.RemoveEmptyEntries);

            foreach (string strInternal in arr_strInternal)
            {
               lst_strStack.Add(++iCounter + ":" + strInternal);
            }

            Console.WriteLine(string.Join(" ", lst_strStack.ToArray()));
         }
      }
   }
}

So, without the file processing, think about this:
Each row will need the counter attached multiple times.
Each line will need to be split, then modified, then re-assembled:

using System;
using System.Collections.Generic;

namespace DW_407604_CS_CON
{
   class Program
   {
      static void Main(string[] args)
      {
         string[] arr_str =
         { //pretend this came from the file into an array
            "2365 6598 8745 5648",
            "5421 5784 9657 4562"
         };

         int iCounter = 0;
         
         foreach (string s in arr_str)
         {
            List<string> lst_strStack = new List<string>();
            
            string[] arr_strInternal = s.Split(" ".ToCharArray(),
               StringSplitOptions.RemoveEmptyEntries);

            foreach (string strInternal in arr_strInternal)
            {
               lst_strStack.Add(++iCounter + ":" + strInternal);
            }

            Console.WriteLine(string.Join(" ", lst_strStack.ToArray()));
         }
      }
   }
}

Thanks for your help...

Here is the complete code....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Merge
    {
        static void Main(string[] args)
        {

            string[] files = Directory.GetFiles(@"F:\New folder\", "*.txt", SearchOption.AllDirectories);

            StringBuilder strFile = new StringBuilder();

            foreach (string file in files)
            {
                using (StreamReader sr = new StreamReader(file))
                {

                    string s = Path.ChangeExtension(file, null);
                    strFile.AppendFormat(s.Substring(s.LastIndexOf(@"\") + 1) + " ");
                    char[] charsToTrim = {' ', '\r', '\n'};
                    string kkj = (sr.ReadToEnd().TrimEnd(charsToTrim));
                    string[] words = kkj.Split(' ');

                    int iCounter = 1;

                    foreach (string word in words)
                    {
                        strFile.Append(iCounter++ + ":" + word + " ");
                    }
                    strFile.AppendLine();
                }
            }

            using (StreamWriter outfile = new StreamWriter(@"F:\New folder\" + @"\FinalOutputFile.txt"))
            {
                outfile.Write(strFile.ToString());
            }
        }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.