C# how to read 2 files using Stream and response both as 1

By : barak
Source: Stackoverflow.com
Question!

I need to read 2 files and somehow combine them and response them both as 1.
I don't want to create a new file containing both files text.
This is my code to response my main file,

FileStream fs = File.OpenRead(string.Format("{0}/neg.acc",
                              Settings.Default.negSourceLocation));
using (StreamReader sr = new StreamReader(fs))
{
   string jsContent = sr.ReadToEnd();
   context.Response.Write(jsContent);
}

I need my 2nd file to be read right after the main is done.

An easy way to explain it:
lets assume main file contains : "hello"
and 2nd file contains: "what a beautiful day"

my response should be:
"hello"
"what a beautiful day"

Thanks in advance

By : barak


Answers

This is what I did, not sure its the right way using C#,

 static public string CombineFilesText(string mainPath, string clientPath)
    {
        string returnText = "";

        FileStream mfs = File.OpenRead(mainPath);
        using (StreamReader sr = new StreamReader(mfs))
        {
            returnText  = sr.ReadToEnd();
        }
        FileStream cfs = File.OpenRead(clientPath);
        using (StreamReader sr = new StreamReader(cfs))
        {
            returnText  = sr.ReadToEnd();
        }

        return returnText;
    }
By : barak


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

class Test
{
    public static void Main()
    {
        string File1 = @"c:\temp\MyTest1.txt";
        string File2 = @"c:\temp\MyTest2.txt";

        if (File.Exists(File1))
        {
            string appendText = File.ReadAllText(File1);
            if (File.Exists(File2))
            {
                appendText  = File.ReadAllText(File2);
            }
        }
    }
}
By : David BS


FileStream is also a disposable object like StreamReader. Best to wrap that in a using statement too. Also to make the code a little more reusable, place the code to read the text file into its own method, something like:

public static string CombineFilesText(string mainPath, string clientPath)
{
    string returnText = ReadTextFile(mainPath);
    returnText  = ReadTextFile(clientPath);

    return returnText;
}

private static string ReadTextFile(string filePath)
{
    using (FileStream stream = File.OpenRead(filePath))
    {
        using (StreamReader reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }
}


This video can help you solving your question :)
By: admin