简体   繁体   English

c# 从许多文件中读取并将其中的一部分写入新文件

[英]c# read from many files and write just part of them into new file

I've try to read many files one by one and write just part of them into new file.我尝试一一读取许多文件并将其中的一部分写入新文件。 I am new in c#, can someone give me some idea, how to do it.我是 c# 的新手,谁能给我一些想法,怎么做。

Here is the code, but in this way only record all files in one main file.这里是代码,但是这样只将所有文件记录在一个主文件中。 I want to get some information with substring from all file, and write this information to main file我想从所有文件中获取 substring 的一些信息,并将这些信息写入主文件

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
    {
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:\Users\Name\Desktop\Files\";
            string[] files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
            using (var output = File.Create(path + "output.txt"))
            {
                foreach (var file in files)
                {
                    using (var data = File.OpenRead(file))
                    {
                        data.CopyTo(output);
                    }
                }

            }
        }
    }
}

You can do it like this for example if you want to use Substring :例如,如果您想使用Substring ,您可以这样做:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:\Users\Name\Desktop\Files\";

            string[] files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);

            //Reads the first lines
            var firstLines = files.Select(f => File.ReadLines(f).First());

            //Cuts from the fifth character and then five characters long
            //Writes the result to the file output.txt
            File.WriteAllLines(path + "\\output.txt", firstLines.Select(l => l.Substring(5, 5)));
        }
    }
}

But you can also use other string manipulation methods like Replace .但您也可以使用其他字符串操作方法,例如Replace

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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