C# 如何读取一个文件夹下的多个文件内容

2024-12-19 10:13:40
推荐回答(2个)
回答1:

System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(“文件夹路径”);
FileInfo[] ff = di.GetFiles("*.txt");//只取文本文档
string ss = "";//存放内容
foreach (FileInfo temp in ff)
{
using (StreamReader sr = temp.OpenText())
{
ss += sr.ReadToEnd();//内容追加到ss中
}
}
File.AppendAllText("要保存的文件路径", ss);//保存到一个文件里

回答2:

using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// 用二进制方式读,以兼容非文本的文件。
using (BinaryWriter bw = new BinaryWriter(File.OpenWrite("c:\\111\\result.txt")))
{
using (BinaryReader br = new BinaryReader(File.OpenRead("C:\\111\\1.txt")))
{
bw.Write(br.ReadBytes((int)br.BaseStream.Length));
}
using (BinaryReader br = new BinaryReader(File.OpenRead("C:\\111\\2.txt")))
{
bw.Write(br.ReadBytes((int)br.BaseStream.Length));
}
using (BinaryReader br = new BinaryReader(File.OpenRead("C:\\111\\3.txt")))
{
bw.Write(br.ReadBytes((int)br.BaseStream.Length));
}
}
}
}
}