简体   繁体   中英

How to find all empty files recursively

How would you find all empty files in a directory that are empty. A given file may have carriage returns or blank spaces. i need to capture those as well. I can can use code in either powershell or c#.

Powershell使它变得容易:

Get-ChildItem -Path C:\\dir -recurse -Filter { $_.Length -eq 0 }

#YOUR HOMEWORK: filter for your CRLF criteria as well

The System.IO have the classes you want

    DirectoryInfo di = new DirectoryInfo("c:\\Luke101");
    FileInfo[] fiArr = di.GetFiles();

    foreach (FileInfo fi in fiArr)
    {
        if(fi.Length == 0)
        {
            //.. Then do stuff
        }
    }
var files = new DirectoryInfo("Your path").GetFiles("*.*", SearchOption.AllDirectories);
foreach(var file in files) 
{
    using(var r = new StreamReader(file.OpenRead()))
    {
       string content = r.ReadToEnd();
       if(string.IsnullOrWhitespace(content))
       {
       // do stuff
       }
    }
}

Code is off the top of my had, didn't test it, by you can get the idea.

Get all zero byte length files or files that has only spaces, tabs, CR from the beginning of the file to the end.

Get-ChildItem <path> -Recurse | 
Where-Object {!$_.PSIsContainer -and ($_.Length -eq 0 -or ([IO.File]::ReadAllText($_.FullName) -match '^\s+$') }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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