简体   繁体   中英

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

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

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);
            }
        }
    }
}

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();
        }
    }
}

seems like your question needs asp.net tag

context.Response.WriteFile(Settings.Default.negSourceLocation + "/neg.acc");
context.Response.WriteFile(Settings.Default.negSourceLocation + "/neg2.acc");

https://msdn.microsoft.com/en-us/library/dyfzssz9

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM