如何合并文件取决于他们的第一个& miidele文件名 [英] How to merge the files depending on their first & miidele name of file

查看:87
本文介绍了如何合并文件取决于他们的第一个& miidele文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在一个文件夹中有一组文本文件。

文本文件名称是

DLPOR_00_01

DLPOR_00_02

DLPOR_01_01

DLPOR_01_02

SLPOR_00_01

SLPOR_00_02



这里我想从文件夹中动态读取文件。我想根据文件的名字和中间名合并文件

例如,我想将DLPOR_00_01和DLPOR_00_02合并为一个文件,因为前2个名称(DLPOR_00)相同。像这样我想合并所有文本文件。





如果有人帮我这个。



谢谢。

Hi,
I have a set of text files in one folder.
Text file Names are
DLPOR_00_01
DLPOR_00_02
DLPOR_01_01
DLPOR_01_02
SLPOR_00_01
SLPOR_00_02

Here i want to dynamically read the file from folder. And i want to merge the files depending on Firstname and middle name of the file
For Example i want to merge the DLPOR_00_01 and DLPOR_00_02 into one file because the first 2 names(DLPOR_00) same. Like this same way i want to merge the all text file.


If anyone help me for this.

Thanks.

推荐答案

示例代码

Sample code
string directory =@"D:\";
string[] fiels = System.IO.Directory.GetFiles(directory);

var fileGroups =fiels.Select(f=>System.IO.Path.GetFileName(f))
       .Where(f=>f.Split('_').Length==3)
       .GroupBy(f=> f.Substring(0,f.LastIndexOf('_'))).ToList();
       
foreach(var g in fileGroups)
{
    string newFileName = g.Key+".txt";
    string newfileContent ="";
    foreach( var f in g)
    {
      newfileContent +=
              System.IO.File.ReadAllText(System.IO.Path.Combine(directory, f));
    }
    System.IO.File.WriteAllText(System.IO.Path.Combine(directory, newFileName), 
                                   newfileContent);
}





我使用过几种LINQ和System.IO方法,如果你不明白,请问。



1.我正在使用 Directory.GetFiles 方法获取目录中的所有文件

2.然后填写并获取格式为 xxxx_xxxx_xx 的文件使用LiNQ,然后根据文件名对结果进行分组,而不是最终编号。

3.循环结果并使用分组文件的内容创建新文件。



I have used several LINQ and System.IO methods, if you you not understand anything please ask.

1. I'm taking all the files in the directory using Directory.GetFiles method
2. then filder and get only the files with the format xxxx_xxxx_xx Using LiNQ and then group the result based on the file name without final number.
3. loop the result and create new file with the content of grouped files.


您需要遍历文件夹中的文件集合,然后比较它们的名称并将它们合并在一起他们的名字符合标准的情况。使用列表< String> [ ^ ]普通班,因为它能够对数据进行排序,搜索和连接。



这是一个例子:如何:枚举目录和文件 [ ^ ]
You need to loop through the collection of files in the folder, then compare their names and merge them in case when their names fulfill the criteria. Use List<String>[^] general class, because it enables to sort, search and concat data.

Here is an example: How to: Enumerate Directories and Files[^]


这篇关于如何合并文件取决于他们的第一个&amp; miidele文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆