c#如何读取2个文件使用流和响应都为1

本文关键字:响应 文件 何读取 读取 2个 | 更新日期: 2023-09-27 18:02:14

我需要读取2个文件,并以某种方式组合它们并将它们都响应为1。
我不想创建一个包含两个文件text的新文件。
这是我的代码来响应我的主文件

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

我需要我的第二个文件被读取后,主要完成。

一个简单的解释:
让我们假设主文件包含:"hello"
第二个文件包含:"what a beautiful day"

我的回答应该是:
"你好"
"what a beautiful day"

Thanks in advance

c#如何读取2个文件使用流和响应都为1

FileStream也是一个像StreamReader一样的一次性对象。最好也将其封装在using语句中。另外,为了使代码更易于重用,可以将读取文本文件的代码放入自己的方法中,例如:

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

似乎你的问题需要asp.net标签

context.Response.WriteFile(Settings.Default.negSourceLocation + "/neg.acc");
context.Response.WriteFile(Settings.Default.negSourceLocation + "/neg2.acc");
https://msdn.microsoft.com/en-us/library/dyfzssz9

这就是我所做的,不确定这是使用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;
    }