欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

LINQ和文件目录

程序员文章站 2023-11-07 15:05:04
记录https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/linq/linq-and-file-directories的学习 查询具有指定扩展名的文件 (SearchOption.AllDirectorie ......

记录的学习

 

查询具有指定扩展名的文件 (searchoption.alldirectories 指递归文件夹获取所有文件)

string startfolder = @"c:\users\bibi\desktop\代码\异步\consoleapp4\test\";
directoryinfo dir = new directoryinfo(startfolder);
ienumerable<fileinfo> filelist = dir.getfiles("*.*", searchoption.alldirectories);

var filequery = from file in filelist
                where file.extension == ".png"
                orderby file.name
                select file;

foreach(var item in filequery)
{
    console.writeline(item.fullname);
}

按扩展名对文件进行分组

// take a snapshot of the file system.  
string startfolder = @"c:\users\bibi\desktop\代码\异步\consoleapp4\test\";

// used in writeline to trim output lines.  
int trimlength = startfolder.length;

// take a snapshot of the file system.  
system.io.directoryinfo dir = new system.io.directoryinfo(startfolder);

// this method assumes that the application has discovery permissions  
// for all folders under the specified path.  
ienumerable<system.io.fileinfo> filelist = dir.getfiles("*.*", system.io.searchoption.alldirectories);

var querygroupbyext = from file in filelist
                      group file by file.extension.tolower() into filegroup
                      orderby filegroup.key
                      select filegroup;

foreach(var group in querygroupbyext)
{
    console.writeline(group.key);
    foreach(var item in group)
    {
        console.writeline($"    {item.name}");
    }
}

求目录下的所有文件的总字节数

string startfolder = @"c:\users\bibi\desktop\代码\异步\consoleapp4\test\";

system.io.directoryinfo dir = new system.io.directoryinfo(startfolder);
var totallength = dir.getfiles().sum(x=>x.length);

console.writeline(totallength+" bytes");

对接文件夹中的文件(序列求等sequenceequal、交集insect、差集except)

string patha = @"c:\users\bibi\desktop\代码\异步\consoleapp4\test\";
string pathb = @"c:\users\bibi\desktop\代码\异步\consoleapp4\test\testx\";

system.io.directoryinfo dir1 = new system.io.directoryinfo(patha);
system.io.directoryinfo dir2 = new system.io.directoryinfo(pathb);

//使用了顶层目录searchoption.topdirectoryonly,不需递归目录下的文件夹寻找文件,只要第一层文件。 ienumerable<system.io.fileinfo> list1 = dir1.getfiles("*.*", searchoption.topdirectoryonly); ienumerable<system.io.fileinfo> list2 = dir2.getfiles("*.*", searchoption.topdirectoryonly); //使用自定义的文件默认比较器 filecompare myfilecompare = new filecompare(); //判断两个序列是否相等 bool isequalone = list1.sequenceequal(list2, myfilecompare); if (isequalone == true) { console.writeline("the two folders are the same"); } else { console.writeline("the two folders are not the same"); } //求交集文件 var querycommonfiles = list1.intersect(list2, myfilecompare); if (querycommonfiles.any()) { console.writeline("the following files are in both folders:"); foreach (var v in querycommonfiles) { console.writeline(v.fullname); //shows which items end up in result list } } //求差集文件 在list1却不在list2的文件 var querylist1only = list1.except(list2, myfilecompare); console.writeline("the following files are in list1 but not list2:"); foreach (var v in querylist1only) { console.writeline(v.fullname); }

 查找目录中最大、最小的一个或多个文件。

using system;
using system.collections.generic;
using system.data;
using system.diagnostics.codeanalysis;
using system.io;
using system.linq;
using system.reflection;

namespace consoleapp4
{
    class program
    {
        static void main(string[] args)
        {
            string startfolder = @"c:\users\mycomputer\desktop\代码\异步\consoleapp4\test\testx\";

            system.io.directoryinfo dir = new system.io.directoryinfo(startfolder);
           
            ienumerable<system.io.fileinfo> filelist = dir.getfiles("*.*", system.io.searchoption.alldirectories);

            //查找文件最大字节数
            long maxsize = filelist.select(x => getfilelength(x)).max();
           
            console.writeline($"the length of the largest file under {startfolder} is {maxsize}");

            //查找字节数最大的文件
            var longestfile = filelist.orderbydescending(x => getfilelength(x)).first();          

            console.writeline("the largest file under {0} is {1} with a length of {2} bytes",
                                startfolder, longestfile.fullname, longestfile.length);

            //查找字节数最小的文件
            var smallestfile = filelist.orderby(x => getfilelength(x)).first();            

            console.writeline("the smallest file under {0} is {1} with a length of {2} bytes",
                                startfolder, smallestfile.fullname, smallestfile.length);

           //查找字节前十大的文件
            var querytenlargest = filelist.orderbydescending(x => getfilelength(x)).take(10);        

            console.writeline("the 10 largest files under {0} are:", startfolder);

            foreach (var v in querytenlargest)
            {
                console.writeline("{0}: {1} bytes", v.fullname, v.length);
            }
        }

        static long getfilelength(system.io.fileinfo fi)
        {
            long bytes;
            try
            {
                bytes = fi.length;
            }
            catch (system.io.filenotfoundexception)
            {
                //如果文件找不到 0字节处理
                bytes = 0;
            }
            return bytes;
        }
    }   
}

查询目录树中重复文件。

using system;
using system.collections.generic;
using system.data;
using system.io;
using system.linq;

namespace consoleapp4
{
    class program
    {
        static void main(string[] args)
        {
            string startfolder = @"c:\users\biubiu\desktop\代码\异步\consoleapp4\test\";
            directoryinfo dir = new directoryinfo(startfolder);           
            ienumerable<system.io.fileinfo> filelist = dir.getfiles("*.*", system.io.searchoption.alldirectories);

            //根据文件名字、最后更新时间、字节长度来判断文件重复
            var querysamegroup = from file in filelist
                                     group file.name by new portablekey { name = file.name, lastwritetime = file.lastwritetime, length = file.length } into filegroup
                                     where filegroup.count() > 1
                                     select filegroup;

            //linq 方法调用写法 
            //var querysamegroup2 = filelist.groupby(file => new portablekey
            //{
            //    lastwritetime = file.lastwritetime,
            //    length = file.length,
            //    name = file.name
            //}, file => file.name).where(filegroup => filegroup.count() > 1);

            foreach(var group in querysamegroup)
            {
                console.writeline(group.key);
                foreach(var item in group)
                {
                    console.writeline($"  {item}");
                }
            }        
        }       
    }

    class portablekey
    {
        public string name { get; set; }
        public datetime lastwritetime { get; set; }
        public long length { get; set; }

        //分组跟这个相关
        public override bool equals(object obj)
        {
            portablekey other = (portablekey)obj;
            return this.lastwritetime == other.lastwritetime &&
                this.length == other.length &&
                this.name == other.name;
        }

        public override int gethashcode()
        {
            string str = $"{this.lastwritetime}{this.length}{this.name}";
            return str.gethashcode();
        }
        public override string tostring()
        {
            return $"{this.name} {this.length} {this.lastwritetime}";
        }
    }
}