Sunday, 2 February 2020

C# - FolderBrowserDialog


// Open rich text files (rtf) into the RichTextBox using the FolderBrowserDialog
// to set the default directory for opening files.
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;

public class FolderBrowserDialogExampleForm : System.Windows.Forms.Form
{
    private FolderBrowserDialog folderBrowserDialog1;
    private OpenFileDialog openFileDialog1;

    private RichTextBox richTextBox1;

    private MainMenu mainMenu1;
    private MenuItem fileMenuItem, openMenuItem;
    private MenuItem folderMenuItem;

    private string openFileName, folderName;

    private bool fileOpened = false;

    // The main entry point for the application.
    [STAThreadAttribute]
    static void Main()
    {
        Application.Run(new FolderBrowserDialogExampleForm());
    }

    // Constructor.
    public FolderBrowserDialogExampleForm()
    {
        this.mainMenu1 = new System.Windows.Forms.MainMenu();
        this.fileMenuItem = new System.Windows.Forms.MenuItem();
        this.openMenuItem = new System.Windows.Forms.MenuItem();
        this.folderMenuItem = new System.Windows.Forms.MenuItem();
       
        this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
        this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
        this.richTextBox1 = new System.Windows.Forms.RichTextBox();

        this.mainMenu1.MenuItems.Add(this.fileMenuItem);
        this.fileMenuItem.MenuItems.AddRange(
                            new System.Windows.Forms.MenuItem[]  {this.openMenuItem,
                                                                 this.folderMenuItem});
        this.fileMenuItem.Text = "File";

        //(1)
        this.openMenuItem.Text = "Open...";
        this.openMenuItem.Click += new System.EventHandler(this.openMenuItem_Click);

        //(2)
        this.folderMenuItem.Text = "Select Directory...";
        this.folderMenuItem.Click += new System.EventHandler(this.folderMenuItem_Click);

        this.openFileDialog1.DefaultExt = "TXT";
        this.openFileDialog1.Filter = "TXT files (*.txt)|*.txt";

        this.folderBrowserDialog1.Description =
                            "Select the directory that you want to use as the default.";
        this.folderBrowserDialog1.ShowNewFolderButton = false;
        this.folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Personal;

        this.richTextBox1.AcceptsTab = true;
        this.richTextBox1.Location = new System.Drawing.Point(8, 8);
        this.richTextBox1.Size = new System.Drawing.Size(280, 344);
        this.richTextBox1.Anchor = AnchorStyles.Top | AnchorStyles.Left |
                                   AnchorStyles.Bottom | AnchorStyles.Right;

        this.ClientSize = new System.Drawing.Size(296, 360);
        this.Controls.Add(this.richTextBox1);
        this.Menu = this.mainMenu1;
        this.Text = "TXT Document Browser";
    }
       
    private void openMenuItem_Click(object sender, System.EventArgs e)
    {      
        if (!fileOpened)
        {
            openFileDialog1.InitialDirectory = folderBrowserDialog1.SelectedPath;
            openFileDialog1.FileName = null;
        }
      
        DialogResult result = openFileDialog1.ShowDialog();
      
        if (result == DialogResult.OK)
        {
            openFileName = openFileDialog1.FileName;
            try
            {
                // Output the requested file in richTextBox1.
                Stream s = openFileDialog1.OpenFile();
                richTextBox1.LoadFile(s, RichTextBoxStreamType.PlainText);
                //richTextBox1.LoadFile(
                //openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
                s.Close();

                fileOpened = true;
            }
            catch (Exception exp)
            {
                MessageBox.Show(
                       "An error occurred while attempting to load the file. The error is:"
                                + System.Environment.NewLine + exp.ToString()
                                + System.Environment.NewLine);
                fileOpened = false;
            }
            Invalidate();           
        }       
        else if (result == DialogResult.Cancel)
        {
            return;
        }
    }  

    private void folderMenuItem_Click(object sender, System.EventArgs e)
    {       
        DialogResult result = folderBrowserDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            folderName = folderBrowserDialog1.SelectedPath;
            if (!fileOpened)
            {              
                openFileDialog1.InitialDirectory = folderName;
                openFileDialog1.FileName = null;
                openMenuItem.PerformClick();
            }
        }
    }
}


Monday, 13 January 2020

C# - Directory.GetFiles() in Created Date/Time Order



Create 3 file (.txt) in C:\File directory in different time to have 3 textfile in different created datetime as below.


using System;
using System.Collections.Generic;
using System.Text;


using System.IO;
using System.Collections;

namespace Console
{
    public partial class clsCompareFileInfo : IComparer
    {
        public int Compare(object x, object y)
        {
            int CompareRet = default(int);
            FileInfo File1;
            FileInfo File2;

            File1 = (FileInfo)x;
            File2 = (FileInfo)y;

            CompareRet = DateTime.Compare(File1.LastWriteTime, 
                                          File2.LastWriteTime);
            return CompareRet;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo dirinfo;
            FileInfo[] allFiles;

            dirinfo = new DirectoryInfo("C:\File");
            allFiles = dirinfo.GetFiles("*.txt");

            Array.Sort(allFiles, new clsCompareFileInfo());

            foreach (FileInfo fl in allFiles)
                System.Console.WriteLine(fl.FullName.ToString());

        }
    }
}


Output

DocumentThree.txt
DocumentOne.txt
DocumentTwo.txt

Wednesday, 8 January 2020

C# - FileSystemWatcher

Example 1


using System;

using System.IO;

namespace TestFileSystemWatcher
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"E:\FileWatcher";
            MonitorDirectory(path);
            Console.ReadKey();
        }

        private static void MonitorDirectory(string path)
        {
            FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
            fileSystemWatcher.Filter = "*.dat";
            fileSystemWatcher.Path = path;
            fileSystemWatcher.Created += FileSystemWatcher_Created;
            fileSystemWatcher.Renamed += FileSystemWatcher_Renamed;
            fileSystemWatcher.Deleted += FileSystemWatcher_Deleted;
            fileSystemWatcher.EnableRaisingEvents = true;
        }

        private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("File created: {0}", e.Name);
        }

        private static void FileSystemWatcher_Renamed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("File renamed: {0}", e.Name);
        }

        private static void FileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("File deleted: {0}", e.Name);
        }

    }

}

Example 2



using System;
using System.IO;
using System.Security.Permissions;


namespace TestFileSystemWatcher
{
    public class Watcher
    {
        public static void Main(string[] args)
        {
            Run();
        }

        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        private static void Run()
        {
            string[] args = Environment.GetCommandLineArgs();

            // If a directory is not specified, exit program.
            if (args.Length != 2)
            {
                // Display the proper way to call the program.
                Console.WriteLine("Usage: Watcher.exe (directory)");
                return;
            }

            // Create a new FileSystemWatcher and set its properties.
            using (FileSystemWatcher watcher = new FileSystemWatcher())
            {
                watcher.Path = args[1];

                // Watch for changes in LastAccess and LastWrite times, and
                // the renaming of files or directories.
                watcher.NotifyFilter = NotifyFilters.LastAccess
                                     | NotifyFilters.LastWrite
                                     | NotifyFilters.FileName
                                     | NotifyFilters.DirectoryName;

                // Only watch text files.
                watcher.Filter = "*.dat";

                // Add event handlers.
                watcher.Changed += OnChanged;
                watcher.Created += OnCreated;
                watcher.Deleted += OnDeleted;
                watcher.Renamed += OnRenamed;

                // Begin watching.
                watcher.EnableRaisingEvents = true;

                // Wait for the user to quit the program.
                Console.WriteLine("Press 'q' to quit the sample.");
                while (Console.Read() != 'q') ;
            }
        }

        // Define the event handlers.
        private static void OnChanged(object source, FileSystemEventArgs e)
        {
            // Specify what is done when a file is changed, created, or deleted.
            Console.WriteLine("File: " + e.FullPath + e.ChangeType);
        }


        private static void OnCreated(object source, FileSystemEventArgs e)
        {
            // Specify what is done when a file is changed, created, or deleted.
            Console.WriteLine("File: " + e.FullPath + e.ChangeType);
        }

        private static void OnDeleted(object source, FileSystemEventArgs e)
        {
            // Specify what is done when a file is changed, created, or deleted.
            Console.WriteLine("File: " + e.FullPath + e.ChangeType);
        }

        private static void OnRenamed(object source, RenamedEventArgs e)
        {
            // Specify what is done when a file is renamed.
            Console.WriteLine("File: " + e.OldFullPath +  "renamed to" + e.FullPath);
        }
    }
}

Monday, 6 January 2020

VBA - Determine if Cells Contain a Specific Value in Excel


Excel Function: COUNTIF()

Code with the IF statement included:

=IF(COUNTIF(A1,"*Yellow*")>0,"Value Found", "Value Not Found")


Code without the IF statement:

= COUNTIF(A1,"*Yellow*")


Find if a Value is in a Range of Cells

= COUNTIF(A1:A5,"*Yellow*")