16 Haz

Download Files Synchronous And Asynchronous From A URL in C#

This page tells how to download files from any url to local disk. To download the files, We use WebClient class in System.Net namespace. This class supports to the synchronous and asynchronous downloads. Following examples show how to download files as synchronous and asynchronous.

This example downloads the resource with the specified URI to a local file.

            using (WebClient webClient = new WebClient())
            {
                webClient.DownloadFile("http://www.example.com/file/test.jpg", "test.jpg");
            }

This example downloads to a local file, the resource with the specified URI. Also this method does not block the calling thread.

            using (WebClient webClient = new WebClient())
            {
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e)
                    {
                        Console.WriteLine("Downloaded:" + e.ProgressPercentage.ToString());
                    });

                webClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler
                    (delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
                    {
                        if(e.Error == null && !e.Cancelled)
                        {
                            Console.WriteLine("Download completed!");
                        }
                    });
                webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");
            }
16 Haz

C# Convert A Numeric Value To Hexadecimal Format

This example shows a numeric value in its hexadecimal format. To do this, we use the x or X formatting specifier. The letter case of the formatting specifier determines whether the hexadecimal letters appear in lowercase or uppercase.

Sample Code 1:

            // Convert numeric value to hexadecimal value
            Console.WriteLine(string.Format("0x{0:X}", 12));
            Console.WriteLine(string.Format("0x{0:X}", 64));
            Console.WriteLine(string.Format("0x{0:X}", 123));
            Console.WriteLine(string.Format("0x{0:X}", 196));
            Console.WriteLine(string.Format("0x{0:X}", 255));
            //Output:
            //0xC
            //0x40
            //0x7B
            //0xC4
            //0xFF

If we want to convert hexadecimal value to numeric value, we can use like below:

Sample Code 2:

            //Convert hexadecimal value to numeric value
            Console.WriteLine(Convert.ToInt32("0xC", 16).ToString());
            Console.WriteLine(Convert.ToInt32("0x40", 16).ToString());
            Console.WriteLine(Convert.ToInt32("0x7B", 16).ToString());
            Console.WriteLine(Convert.ToInt32("0xC4", 16).ToString());
            Console.WriteLine(Convert.ToInt32("0xFF", 16).ToString());
            //Output:
            //12
            //64
            //123
            //196
            //255
15 Haz

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 Haz

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 Haz

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))]