15 Jun

C# Get Hidden Files In A Directory

This example list all hidden files on the specified path.

Code Sample:

            //Suppose we have this sample directory and files

            //C:\TestDirectory\Files\file1.txt
            //C:\TestDirectory\Files\file2.txt //Hidden
            //C:\TestDirectory\Files\file3.txt
            //C:\TestDirectory\Files\file4.txt //Hidden
            //C:\TestDirectory\Files\file5.txt

            string[] filePaths = Directory.EnumerateFiles(@"C:\TestDirectory\Files\").
                                           Where(f => (new FileInfo(f).Attributes & FileAttributes.Hidden) == FileAttributes.Hidden).
                                           ToArray();
            foreach (string file in filePaths)
                Console.WriteLine(file);
            //Output:
            //C:\TestDirectory\Files\file2.txt
            //C:\TestDirectory\Files\file4.txt
15 Jun

Select Specific Nodes From XML Using XPath in C#

This example shows how to use an XPath expression in C#. In the sample code, there are two queries. The first of them selects top 2 nodes(vegetable) from xml document. Another query selects price nodes with price > 15. To select nodes from XML, we use the method “XmlDocument.Selec­tNodes” in System.Xml namespace. Then we pass XPath expression as a parameter.

            
            //Suppose we have this XML file.
            string xml =
               "" +
               "    " +
               "        Pepper" +     
               "        10" +
               "    " +
               "    " +
               "        Onion" +     
               "        20" +
               "    " +
               "    " +
               "        Garlic" +     
               "        5" +
               "    " +
               "    " +
               "        Corn" +     
               "        35" +
               "    " +
               "";

            //
            // Creates an XmlDocument to load the xml data.
            //
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xml);

            //
            // Select top 2 vegetables from the xml document.
            //
            string expression = "/Vegetables/Vegetable[position() <= 2]";
            XmlNodeList nodes = xmlDocument.SelectNodes(expression);
            foreach (XmlNode node in nodes)
            {
                Console.WriteLine("Vegetable: {0}", node["Name"].InnerText);
            }
            //Output:
            //Vegetable: Pepper
            //Vegetable: Onion

            //
            // Select price nodes with price > 15
            //
            expression = "/Vegetables/Vegetable[Price>15]/Price";
            nodes = xmlDocument.SelectNodes(expression);
            foreach (XmlNode node in nodes)
            {
                Console.WriteLine("Price: {0}", node.InnerText);
            }
            //Output:
            //Price: 20
            //Price: 35 
14 Jun

Most Useful and Most Commonly Used Attributes in C#

This example shows the attributes that are most commonly used and most useful in C#.

        //mark types and members of types that should no longer be used
        [Obsolete("Don't use")]

        //Specifies the display name for a property, event, or public void method which takes no arguments.
        [DisplayName("Web Site Url")]

        //Specifies a description for a property or event.
        [Description("Web site url description")]

        //Specifies the default value for a property.
        [DefaultValue("https://csharpexamples.com")]

        //indicates that a class can be serialized. This class cannot be inherited.
        [Serializable]

        //controls XML serialization of the attribute target as an XML root element.
        [XmlRoot]

        //indicates that a public field or property represents an XML element when the XmlSerializer serializes or deserializes the object that contains it.
        [XmlElement]

        //specifies that the XmlSerializer must serialize the class member as an XML attribute.
        [XmlAttribute]

        //instructs the Serialize method of the XmlSerializer not to serialize the public field or public read/write property value.
        [XmlIgnore]

        //controls accessibility of an individual managed type or member, or of all types within an assembly, to COM.
        [ComVisible(false)]

        //which allows you to hide properties
        [Browsable(false)]

        //tells the designer to expand the properties which are classes 
        [TypeConverter(typeof(ExpandableObjectConverter))]

14 Jun

C# Simple Delegate and Event Example

A delegate is a reference type like the other reference types. But instead of referring to an object, a delegate refers to a method. Following example shows event and delegate usage in C#.

Usage:

            EventDelegateExample e = new EventDelegateExample();
            e.ShowedMessage += new EventDelegateExample.MyCustomEventHandler(delegate(string message) 
                {
                    Console.WriteLine("A new message:" + message);
                });

Example:

    class EventDelegateExample
    {
        public delegate void MyCustomEventHandler(string message);
        public event MyCustomEventHandler ShowedMessage;

        public void ShowNewMsg(string s)
        {
            if (ShowedMessage != null)
                ShowedMessage(s);
        }
    }
14 Jun

C# Multithread Singleton Pattern Example

The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is important when exactly one object is needed to coordinate actions across the system. Following example allows only a single thread to enter the critical area.

    public sealed class Singleton
    {
        private static volatile Singleton _instance = null;
        private static object _syncRoot = new Object();

        /// 
        /// Constructor must be private.
        /// 
        private Singleton() { }

        public static Singleton Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncRoot)
                    {
                        if (_instance == null)
                            _instance = new Singleton();
                    }
                }
                return _instance;
            }
        }
    }