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.
- 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
- {
- // ignored
- }
- 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
- {
- // You can add a custom throw, or ignore
- }
- 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);
- }
- }
- 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();
- }
- }
- }
- if (@"C:\Windows\System32\Notepad.exe".NotFileExist())
- {
- // do something
- }

Viknaraj ManogararajahPosted Jul 19, 2018, 6:32 AM
Nice Article...........