0

Im new to C# but learning as I go forward, so forgive me if my question might be a little too easy for most of you guys. :-)

My question has two parts.

  • First: I have three textfiles (with fixed names) with totaly different contents. I now want these combine into one single textfile.

  • Second: During this combination process I also want every comma(,)
    in these files to be changed to a dot(.) in the output combined file.

I have managed to do something similar with StreamReader and StreamWriter in combination with ReadLine in vb but cant get it to work in C#.

Im thankful for any help I can get.

/Tomas

skr
  • 2,146
  • 19
  • 22
  • 1
    read the 3 files to string (google it, its not hard) do a `.Replace` for your `,` `.` and just `+` them to each other – EpicKip Jul 18 '17 at 09:37

3 Answers3

4

If files are not big you can use this snippet:

File.WriteAllText("newfile", String.Concat(File.ReadAllText("file1"),File.ReadAllText("file2"),File.ReadAllText("file3")).Replace(",","."));
Cihan Yakar
  • 2,402
  • 28
  • 30
2

In general case when files are long with arbitrary number of files you can try Linq SelectMany:

 using System.IO; 
 using System.Linq; 

 ...

 string[] fileNames = new string[] {
   @"C:\MyFile1.txt", 
   @"C:\MyFile2.txt",
   @"C:\MyFile3.txt", 
 };

 ...

 File.WriteAllLines(@"C:\MyCombinedFile.txt", fileNames
   .SelectMany(file => File.ReadLines(file))
   .Select(line => line.Replace(',', '.')));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0
string[] files = new string[]{ @"E:\myfile1.txt", @"E:\myfile2.txt", @"E:\myfile3.txt" };

        string fileContent = string.Empty;
        foreach (var fileName in files)
        {
            using (System.IO.StreamReader Reader = new System.IO.StreamReader(fileName))
            {
                fileContent += Reader.ReadToEnd();
            }
        }
        fileContent = fileContent.Replace(',', '.');

        System.IO.File.WriteAllText(@"E:\myfile.txt", fileContent);
Praboda
  • 520
  • 6
  • 12