Delete oldest Files in directory - c#

I have a question about deleting oldest file in a directory.
Situation is as follows:
I would like to limit the amount of files in a directory to 5 files. Once that limit is reached I would like it to find the oldest file in the directory and delete it, so that the new file can be copied in.
I have been told to use filewatcher, however I have never used that function before.

using System.IO; using System.Linq;
foreach (var fi in new DirectoryInfo(#"x:\whatever").GetFiles().OrderByDescending(x => x.LastWriteTime).Skip(5))
fi.Delete();
Change the directory name, the argument in Skip(), and LastWriteTime to however you define 'oldest'.
The above gets all the files, orders them youngest first, skips the first 5, and deletes the rest.

You can use DirectoryInfo.EnumerateFiles to get the files in the folder, order them by CreationTime with Enumerable.OrderByDescending, use Enumerable.Take(5) to get the 5 last created files. If there are more the List.ForEach will delete them.
var files = new DirectoryInfo("path").EnumerateFiles()
.OrderByDescending(f => f.CreationTime)
.Skip(5)
.ToList();
files.ForEach(f => f.Delete());

Related

How to programatically use GroupBy and GroupView in windows folder?

I have lot of folders in windows. In each of the folder there are Image/Videos/Excel/Word/PS/Cad..etc.
Im accessing each file programatically, but when I select the folder each time I tend to manually selecting GroupBy="Date Access", GroupView="Details", add a column="date modified". I cant find a way of saving a customized folder settings in my folders.
Is it possible in c#? I'm using Windows 10.
Yes, it is possible in C# to group files by date-accessed or date-modified.
In following example I'll show you how to group using year of creation-date.
First you need to get file infos:
// get file-infos for all files in D:\Daten
string[] files = Directory.GetFiles(#"D:\Daten");
// and convert them to file-info-objects
List<FileInfo> filesWithFileInfo = files.Select(it => new FileInfo(it)).ToList();
Then you can use GroupBy of Linq to group them by year of create date:
List<IGrouping<int, FileInfo>> filesGroupedByYear = filesWithFileInfo.GroupBy(it => it.CreationTime.Year).ToList();
And this enumerates over all groups and then over files in every group:
foreach(IGrouping<int,FileInfo> filesOfOneYear in filesGroupedByYear)
{
Console.WriteLine($"{filesOfOneYear.Count()} Files of year {filesOfOneYear.Key}:");
foreach(FileInfo file in filesOfOneYear.ToList())
{
Console.WriteLine($"{file.Name}");
}
}

File in a folder for X time

here is a scenario:
I copy a file to a folder
and I expect it to be taken by other program.
is there a way to monitor the time that a file exists in a folder
I want to raise an event in case the file is in the folder over X time
Please advise what can I use to accomplish that
I had in mind using File system watcher and save the time of it created
and compare if the file exists after X time
If you only care about timeout, then simply check for it after copying. E.g. using a Timer:
var timer = Timer(5000);
timer.Elapsed += (s, a) =>
{
// checking if file is still there
if(File.Exists(...)
{
// do something
}
}
timer.Start();
Depending on how precise you need to be, you could just have a process that checks the contents of the folder every so often and lets you know about any files that have been in the folder for too long.
To list files in a directory you could use Directory.GetFiles as below.
Then iterate thru all the files checking for file age.
string[] files = System.IO.Directory.GetFiles("c:\temp", "*.txt", System.IO.SearchOption.TopDirectoryOnly);
foreach(string file in files)
{
if (System.DateTime.UtcNow.Subtract(System.IO.File.GetCreationTimeUtc(file)).TotalMinutes > 5)
System.Diagnostics.Debug.WriteLine("TODO: Alert, file older than 5 minutes...");
}

Reading files using system.io?

Could do with some help with this question.I am using the system.io, and I have to do things which require files to be moved, grouped, renamed. .
Working in command line application using c# so far I have moved some files from one directory to another, I now need to group some pdf files like so - B-12345 1.pdf, B-12345 2.pdf, B-12345 3.pdf, B-12345 4.pdf.I have been told I dont need to physically group them together just for the purposes of ensuring I only create one job per project reference(b-1234).
To give you a bit of background info on what im doing after these files are grouped I need to create a record in the job table sql database.But thats another question for another day just thought id give you some more info.
Mainly I just need info on how to read files that are in a file directory and grouping files, this would be very beneficial to me.?
To make the question a bit clearer this is the order in tasks should be done in the command line app.
Read files in directory (I have moved them so unsure on this?)
Group by project no (unsure)
Create job record in sql db
Move and rename file to correct location
Thanks in advance
My code is below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
public class MoveForProcessing
{
static void Main()
{
// move cad jobs to processing directory and delete former folder, use the System.IO.Path class.
System.IO.Directory.Move(#"C:\Users\Ben\My Documents\Temp\", #"C:\Users\Ben\My Documents\Processing\");
}
}
You could first declare a DirectoryInfo class of the dirctory in question
private System.IO.DirectoryInfo dir = System.IO.DirectoryInfo.Open(#"path");
Then get an array of FileInfo objects for each file in the directory
private FileInfo[] files = dir.GetFiles();
You could also put a wildcard string into GetFiles() if you want only certain file types
private FileInfo[] files = dir.GetFiles("*.pdf");
Then you can increment through the array doing whatever you need with each FileInfo object
foreach(FileInfo f in files)
{
f.Move(); // or whatever you need to do
}

How can I retrieve all files sizes of a folder based on file name and/or extension?

I have a form where the user navigates to a specific folder. The folder they navigate to will have many folders inside it, and within several levels of folders there will be a zip file named "file.zip". So this means there are going to be many folders all which have inside them a "file.zip". I want to scan the chosen folder for all of these "file.zip" files. I will eventually be looking for only those "file.zip" files that have a size of 0kb or is empty. I imagine that I will need to use LINQ to return a list of the files in the parent folder like this:
string[] files = Directory.GetFiles(txtbxOldFolder.Text)
.Select(f => Path.GetFiles(f))
.ToArray();
But I also need their respective sizes so I can later create a list of the directory of any zip files that is empty or shows a size of 0kb. I'm thinking that perhaps there is a way to return the directory AND the size of each file based on name (file.zip) so that I can later go through the array and create a log of the directories for those file.zips that are empty/have a size of 0kb.
var directory = #"c:\myfolder";
var files = Directory.GetFiles(directory, "file.zip", SearchOption.AllDirectories)
.Select(name => new FileInfo(name))
.Where(f => f.Length == 0).ToArray();

C# - Autozip files in a folder based on Year-Month

IT has been tasked with reducing the file-server usage rate so I'd like to do my part my compressing old files(ie Excel/Access/Txt).
We have some folders that contain thousands of files so I don't want to just zip the whole directory into one large file - it would be preferrable to have a number of smaller files so that it would be easier for a user to find the data 'bucket' they are looking for.
Is there a way using C# to read through a directory and zip the files into year-month groups (all files from year-month placed together in one zip)?
Or would it be better to use a script like AutoIT?
Or are there programs already existing to do this so I don't have to code anything?
Im not sure if your question is about zipping, selecting files from particular year/month or both.
About zipping Peter already mentioned 7-zip and SharpZipLib. I have personally only experience with the latter but its all positive, easy to work with.
About grouping your files it could be done by iterating all the files in the folder and group them by either there created date or last modified date.
pseudo:
var files = new Dictionary<DateTime, IList<string>>();
foreach (var file in Directory.GetFiles(...)) {
var fi = new FileInfo(file);
var date = fi.CreatedDate();
var groupDate = new DateTime(date.Year, date.Month);
if (!files.ContainsKey(groupDate)) files.Add(groupDate, new Collection<string>());
files[groupDate].Add(file);
}
now your should have a dictionary containing distinct year/month keys and foreach key a list of files belonging to that group. So for zipping
pseudo:
foreach (var entry in files) {
var date = entry.Key;
var list = entry.Value;
// create zip-file named date.ToString();
foreach (var file in list) {
// add file to zip
}
}
Surely you can do this with a bit of C# and libraries like 7-zip or SharpZipLib.
You could use System.IO.Directory.GetFiles() to loop through the files on each directory, parsing out by file name and adding them to a 7-zip or SharpZipLib object. If it's thousands of files it might be best to throw it in a service or some kind of scheduled task to run overnight so as not to tax the fileshare.
Good luck to you !
EDIT: As an addendum you could use a System.IO.FileInfo object for each file if you need to parse by created date or other file attirbutes.

Categories

Resources