How to programatically use GroupBy and GroupView in windows folder? - c#

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}");
}
}

Related

How can I sort file explorer by date in C#?

In a WPF application, I did open the file explorer.
I use this code.
string filePath = DataManager.OptionData.Workspace;
Process.Start(filePath);
However, I want to sort file explorer by date in code.
I want to show the users an file explorer window that is sorted by date.
Is it possible?
I suggest you to go through below reference links:
Extend OpenFileDialog and SaveFileDialog the easy way
OpenFileDialog file sorting
If you want to do in OpenFileDialog then you have to create a custom dialog and then use the Win32 API calls to modify default behavior of
the dialog.
How to Open a Directory Sorted by Date? -- This is another possible pragmatically possible way which #Parrish Husband suggested:
DirectoryInfo dir = new DirectoryInfo(#"C:\Windows");
FileInfo[] files = dir.GetFiles();
Array.Sort(files, (x, y) => x.LastWriteTimeUtc.CompareTo(y.LastWriteTimeUtc));
Something like this could work for showing the files in order.
var dirInfo = new DirectoryInfo(filePath)
var files = dirInfo.EnumerateFiles(filePath).OrderBy(f => f.CreationTime);
However simply opening an explorer window is probably not what you're aiming for. Are you wanting the user/player to select certain files?

Search for config file upon login

I have a quiz that has a login feature but, when you change pc you must also change the drive the file is located e.g D drive, E drive etc...
Currently its set to F. Is there something i can add that will make it automatically search each drive for the file?
Here is my code
if (File.Exists(#"F:\C# Completed quiz\adam new\Mario quiz\bin/PlayerDetails.txt"))
{
string[] lines = File.ReadAllLines(#"F:\C# Completed quiz\adam new\Mario quiz\bin/PlayerDetails.txt");
I'd recommend you just put it in the AppData or MyDocuments folder:
string filename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "C# Completed quiz","adam new","Mario quiz","bin","PlayerDetails.txt");
//or Environment.SpecialFolder.MyDocuments
if (File.Exists(filename))
{
string[] lines = File.ReadAllLines(filename);
}
you need to enumerate the hard drives on the system and inspect them one at a time
https://msdn.microsoft.com/en-us/library/system.io.directory.getlogicaldrives(v=vs.110).aspx
shows how to enumerate the hard drives on the system
This answer uses what looks like a better way
How can I determine if a given drive letter is a local/mapped/usb drive?
Once you know a drive is a mounted drive the you should look at <drive>:/<your path>
Use Resource file to store your txt inside the application or just distribute it with your executable. To add resource file:
Right click on your project and select Properties
Go to Resources tab and create new file
Click Add resource -> Add Existing File...
Choose your text file and click Open
The file can now be accessed like string:
var lines = Properties.Resources.PlayerDetails;
If the file is in the same folder as your exe then you can access it in this way:
var lines = File.ReadAllLines("PlayerDetails.txt");
Edit: Note the comment below if you prefer to use this method.

Delete oldest Files in directory

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());

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