17 Haz

Print Fibonacci Sequence With Recursive And Iteratively In C#

Fibonacci sequence is a sequence of numbers where the next number is the sum of the previous two numbers behind it. It has its beginning two numbers predefined as 0 and 1. The sequence goes on like this:
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377…

Usage:

            Console.WriteLine("Iterative:");
            for (int i = 0; i < 15; i++)
            {
                Console.Write(CalculateFibonacciNumberIteratively(i) + " ");
            }

            Console.WriteLine();
            Console.WriteLine("Recursive:");
            for (int i = 0; i < 15; i++)
            {
                Console.Write(CalculateFibonacciNumberRecursively(i) + " ");
            }

            //Output window is like follow.

            //Iterative:
            //0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
            //Recursive:
            //0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Iterative Method:

        private int CalculateFibonacciNumberIteratively(int n)
        {
            int result = 0;
            int previous = 1;

            for (int i = 0; i < n; i++)
            {
                int temp = result;
                result = previous;
                previous = temp + previous;
            }
            return result;
        }

Recursive Method:

        private int CalculateFibonacciNumberRecursively(int n)
        {
            if (n == 0)
                return 0;
            else if (n == 1)
                return 1;
            else
                return CalculateFibonacciNumberRecursively(n - 2) + CalculateFibonacciNumberRecursively(n - 1);
        }
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