I started programming in Clipper in the summer of 87. When they released Clipper 5.x, this was a big change at that time. The programming engines were open (like precompiled code) to programmers creating their own commands, with #xtranslate and #xcommand.
When ExtensionMethod was released in C#, see here, I do remember in Clipper, we could extend the native language with our own resources and methods.
In this post, we'll use ExtensionMethod to manipulate the files and folders, in an intuitive and fast way.
If you write WinForms applications, probably, you’ll manipulate the files. Then why create too many variables to handle fixed file names on the hard drive?
I presume that you've read the link above and know how to create an Extension Method class, so I’ll be direct and show the source code.
This code is the code that I use. I just translated the name vars from Portuguese to English.
ExtensionMethodIO.cs
- namespace System.IO
- {
- public static class ExtensionMethodIO
- {
- public static bool FileExist(this string cFile) => File.Exists(cFile);
-
- public static bool NotFileExist(this string cFile) => !File.Exists(cFile);
-
- public static bool MkDir(this string cNewDir)
- {
- try
- {
- if (!Directory.Exists(cNewDir))
- Directory.CreateDirectory(cNewDir);
- return true;
- }
- catch
- {
-
- }
-
- return false;
- }
-
- public static bool CopyFile(this string source, string target)
- {
- try
- {
- File.Copy(source, target, true);
- var fo = new FileInfo(source);
- var fd = new FileInfo(target);
- if (fo.Length != fd.Length)
- return false;
- }
- catch
- {
-
-
- }
-
- return target.FileExist();
- }
-
- public static string GetFileName(this string cFileName) => Path.GetFileName(cFileName);
- public static bool NotDirExist(this string dirName) => !Directory.Exists(dirName);
- public static bool DirExist(this string dirName) => Directory.Exists(dirName);
- public static void ShellOpen(this string file) => Diagnostics.Process.Start(file);
-
- }
- }
Program.cs
- using System.IO;
- using System.Windows.Forms;
-
- namespace ConsoleApp2
- {
- class Program
- {
- static void Main(string[] args)
- {
- var notepad = @"C:\Windows\System32\Notepad.exe";
-
- if (notepad.NotFileExist())
- {
- MessageBox.Show("Notepad is missing!");
- return;
- }
-
- var wd = @"C:\WorkPath";
- if (wd.MkDir())
- {
-
- if (!notepad.CopyFile($@"{wd}\{notepad.GetFileName()}"))
- {
- MessageBox.Show("Copy error!");
- return;
- }
- }
-
- notepad.ShellOpen();
- }
- }
- }
Other ways to use it,
- if (@"C:\Windows\System32\Notepad.exe".NotFileExist())
- {
-
- }
Conclusion
With this small sample, you can expand as per your own requirement. I've more I/O implementations on production but you can do it as per your own needs.
Note
The attached file contains this code working in a console app.