How I Organise My Downloads Folder With .Net Core (C# Automation)

Recently, I felt overly annoyed by my messy download folder on my personal computer. There were too many files, and it was in a total mess. I thought to write a simple bot to address this problem.

The Solution

Solution is a Bot that loops the download,desktop or any other folder and determines the file type for each and every file. Subsequently, it creates a folder for that file type. All files with the same file type will be transferred to this folder and or Organise by Date.

We use .Net Core to make it cross platform. but same code work well for .Net Framework ,.Net Standard and on Xamarin so it work on every popular device today.

Start

let start it by creation new project and initialize git.

dotnet new console -o “FileOrganizer”
git init
git add *.*

Working

.Net provide FileSystemWatcher to watch for changes in a specified directory. You can watch for changes in files and sub directories of the specified directory. You can create a component to watch files on a local computer, a network drive, or a remote computer.

The FileSystemWatcher does not raise events for CDs and DVDs, because time stamps and properties cannot change. Remote computers must have one of the required platforms installed for the component to function properly.

using (FileSystemWatcher watcher = new FileSystemWatcher())
{
watcher.Path = WatchPath;
watcher.Filter = "*.*";
watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime;

watcher.Created += OnCreated;
watcher.EnableRaisingEvents = true;

Console.WriteLine("Press 'q' to quit.");
while (Console.Read() != 'q') ;
}

private static void OnCreated(object sender, FileSystemEventArgs e)
{
}

Move File

we make directory in Organised path such as File Type , year , Mount and then date.

private static void OnCreated(object sender, FileSystemEventArgs e)
{
string watchFilePath = e.FullPath;
string Extension = Path.GetExtension(watchFilePath).Substring(1);
if (orgSubPaths.ContainsKey(Extension.ToLower()))
{
MoveFile(watchFilePath, orgSubPaths[Extension.ToLower()],Extension);
}
else
{
MoveFile(watchFilePath, "UnKnown",Extension);
}
}

private static void MoveFile(string watchFilePath, string orgSubPath,string Extension)
{
DateTime now = DateTime.Now;
string year = now.Year.ToString();
string month = now.ToString("MMMM");
string day = now.ToString("dd");

string FileName = Path.GetFileName(watchFilePath);
string path2ndPart = $@"{orgSubPath}\{year}\{month}\{day}\";
string FullDirectoryPath = Path.Combine(OrgPath, path2ndPart);

Directory.CreateDirectory(FullDirectoryPath);
File.Move(watchFilePath, OrgEdPath);
}

Error One

it work fine but when it overwrite file with same name, so we add check.

string OrgEdPath = Path.Combine(FullDirectoryPath, FileName);
if(File.Exists(OrgEdPath)){
FileName = $"{Path.GetFileNameWithoutExtension(OrgEdPath)}-{now.Minute}{now.Second}.{Extension}";
OrgEdPath = Path.Combine(FullDirectoryPath, FileName);
}

Error Two

when file is other press it throw exception to overcome this problem we try to reach file until file is open to move.

private static bool IsFileLocked(string FilePath, bool del = false)
{
bool locked = false;
try{
FileStream fs = File.Open(FilePath,FileMode.OpenOrCreate,FileAccess.ReadWrite,FileShare.None);
fs.Close();
if(del)
File.Delete(FilePath);
}
catch(Exception){
locked = true;
}
return locked;
}

//so add new lines in MoveFile function.
while(IsFileLocked(watchFilePath) || IsFileLocked(OrgEdPath,true));
File.Move(watchFilePath, OrgEdPath);

Addition

so we have to add configuration file to add or update information with out making changes in code and generate logs of files with time.

string[] Config = File.ReadAllLines("Config.csv");

WatchPath = Config[0].Split(',')[1];
OrgPath = Config[1].Split(',')[1];

orgSubPaths = new Dictionary<string, string>();
for(int i = 2;i < Config.Length;i++)
{
string[] ExtensionOrgSubPath = Config[i].Split(',');
orgSubPaths.Add(ExtensionOrgSubPath[0], ExtensionOrgSubPath[1]);
}

//Add this to end of MoveFunction
File.AppendAllText("Log.csv",$"{now},{watchFilePath},{OrgEdPath}{Environment.NewLine}");


Config File

WatchPath,D:\test\watch
OrgPath,D:\test\org
txt,Wordprocessorandtextfile
zip,Compressedfile
7z,Compressedfile
rar,Compressedfile
csv,Dataanddatabasefile
bmp,Imagefile
gif,Imagefile
jpeg,Imagefile
jpg,Imagefile
png,Imagefile
doc,Wordprocessorandtextfile
docx,Wordprocessorandtextfile
rtf,Wordprocessorandtextfile
mkv,Videofile
mp4,Videofile

Video Tutorial On Youtube


Latest From Our Blog

Shopify Web Development:

Card image cap

2022-03-01 12:59:57

To help our clients reach their business objectives, we provide complete Shopify web development services. Our Shopify developers at MS Solu...

Read more

Bigcommerace Web Development:

Card image cap

2022-03-01 08:01:34

Web development for Bigcommerace:BigCommerce is a feature-rich, hosted platform with a hosted SaaS pricing model. The ease of use and scalab...

Read more

WooCommerce Web Development:

Card image cap

2022-02-09 07:29:36

“Collaborate, organize and build work with MS solutions from virtually anywhere. It's a remote-friendly team workspace where knowledge and c...

Read more
UK Office

78 Plough Road London SW11 2AR78

Tel: +44-74-414-292-94


US Office

5415 Sugarloaf Parkway, Ste 1108 #2889 Lawrenceville, Georgia 30043

Tel: +1-25-13-580-370


UAE Office

Dubai Internet City, 1st Floor, Building Number 12, Premises ED 29, Dubai, UAE

Tel: +44 7441429294


Pakistan Office (Lahore)

MS Solution(Pvt)Ltd., office no 105,2nd floor, Chaudhary center, 168 Multan Road Lahore, Punjab, 54000

Tel: +92-42-37-481-119


Pakistan Office (Multan)

House # 434 ,Street# 8, Block-K, New Multan, Shah Rukn-e-Alam Colony,Multan

Tel: +92-61-67-714-81


Pakistan Office (Islamabad)

Spring north Commercial Bahria town, Phase 7 Islamabad, Islamabad Capital Territory 44000

Tel: +92-32-14-048-436


© 2015 - 2022, MS solution Software Inc., All Rights Reserved.

Privacy Policy and Terms of Use
Cookie Policy

Follow us on