During my work as a software maintainer, I often find myself writing code not as a part of my regular work, but rather to automate tasks that by definition are done manually. As I wrote last time, I despise repetitive tasks, so I created few tools to automate things like checking status of data I've sent to being processed.
Why do I need to use locations like Desktop?
While coding one of those automation tools, I often found myself using locations like a desktop or my home directory to store some data needed by my console applications, which are run either by task scheduler or are added to my context menu and used on a specific directory.
One time I specifically decided to use Desktop, but I was worried that if I have to run it on a different computer (say, company will give developers new laptops) it would stop working and require recompiling. That's when I discovered a beautiful thing in .NET:
System.Environment.SpecialFolder
This is just a simple enum with fields like Desktop, Cookies, Fonts and others. It allows you to access any directory from this enum by simply choosing one of those fields in another Environment class method:
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
which returns string with path to a given directory. Keep in mind, that SpecialFolder is just an Enum, so by itself it will only return a number, not a path!
Note that some paths from this Enum will work only on Windows, while others might return confusing results on Linux systems - so your experience might be different from mine.
Summary
- If you need to quickly get a path to a place like Desktop or user home directory, you can use Environment.SpecialFolder to make it easier.
- You can check the full list of SpecialFolder fields on its Microsoft page.
- If you're deploying it on different OS than Windows, always check what kind of results you can expect using SpecialFolder.
- You can find some more information about using SpecialFolder on Linux on this blogpost. Note: It's for .NET Core 2.1
Top comments (0)