Search code examples
c#filesplitstreamstreamreader

Joining two files in C#, split options


I am currently trying to work on files, joining multiple of them and having problem because the last work from file 1 is linked with first word from file 2. For example:

File 1:John has got new haircut

File 2: Mike has got new haircut

and it prints me "haircutMike".

The code I am using to split words:

        input.Split(' ').ToList().ForEach(n =>{});

I am also making one big file from multiple ones like so:

string[] files = { "f1.txt", "f2.txt" };
        FileStream outputFile = new FileStream("new.txt", FileMode.Create);

        using (StreamWriter ws = new StreamWriter(outputFile))
        {
            foreach (string file in files)
            {
                ws.Write(System.IO.File.ReadAllText(file) + " ");
            }
        }

@EDIT

Changed some code, of course I meant to use stream not binary,also I am using split because I want to count the number of each word in files so I have to split spaces, dots etc.

You mentioned to use + " " option, although it works, but it added me 1 letter to the total count.


Solution

  • EDIT: for multiple input files:

     string[] files = { "f1.txt", "f2.txt" };
    
     var allLines = files.SelectMany(i => System.IO.File.ReadAllLines(i));
    
     System.IO.File.WriteAllLines("new.txt", allLines.ToArray());