13 Haz

C# Copy Stream Examples

Best ways to copy between two stream are like below. There is no special method for .NET Framework 3.5 and before. We writes a sample method using Read and Write methods in Stream class. But .NET Framework 4.0 and later, some methods are added to framework api.

        /// 
        /// code examples for .NET 3.5 and before
        /// 
        /// 
        /// 
        public static void CopyStream(Stream input, Stream output)
        {
            byte[] buffer = new byte[32768];
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);
            }
        }

From .NET 4.0 on, there’s is the Stream.CopyTo method

            Stream inputStream = null;
            Stream outputStream = null;
            inputStream.CopyTo(outputStream);
13 Haz

C# Get File List From Directory

Directory.GetFiles in System.IO namespace returns a string array contains the full paths of all the files contained inside the specified directory. This method can be used.
Sample directory and file structure is like below:
“C:\TestDirectory\Files\file1.png”
“C:\TestDirectory\Files\file2.avi”
“C:\TestDirectory\Files\file3.jpg”
“C:\TestDirectory\Files\SubFolder\file4.jpg”
“C:\TestDirectory\Files\SubFolder\file5.avi”

This example writes the name of files from a directory.

            string[] filePaths = Directory.GetFiles(@"C:\TestDirectory\Files\");
            foreach (string file in filePaths)
                Console.WriteLine(file);
            
            // Result:
            // "C:\TestDirectory\Files\file1.png"
            // "C:\TestDirectory\Files\file2.avi"
            // "C:\TestDirectory\Files\file3.jpg"

Also you can add search pattern. Second parametre is search string to match against the names of files in path. The parameter cannot end in two periods (“..”) or contain two periods (“..”) followed by System.IO.Path.DirectorySeparatorChar or System.IO.Path.AltDirectorySeparatorChar, nor can it contain any of the characters in System.IO.Path.InvalidPathChars.

            string[] filePaths = Directory.GetFiles(@"C:\TestDirectory\Files\", "*.avi");
            foreach (string file in filePaths)
                Console.WriteLine(file);

            // Result:
            // "C:\TestDirectory\Files\file2.avi"

“Directory.GetFiles” method includes only the current directory in a search as default. If you want to search all subdirectories, you can set the search option as third parameter(SearchOption.AllDirectories).

            string[] filePaths = Directory.GetFiles(@"C:\TestDirectory\Files\", "*.avi", SearchOption.AllDirectories);
            foreach (string file in filePaths)
                Console.WriteLine(file);
            
            // Result:
            // "C:\TestDirectory\Files\file2.avi"
            // "C:\TestDirectory\Files\SubFolder\file5.avi"

For .NET Framework 4.0 and layer, you can use this example.

            //For .NET 4.0 and later,
            var filePaths = Directory.EnumerateFiles(@"C:\TestDirectory\Files\").Where(s => s.EndsWith(".avi"));
            foreach (string file in filePaths)
                Console.WriteLine(file);

            // Result:
            // "C:\TestDirectory\Files\file2.avi"
13 Haz

C# Send an Email Using Outlook Program

To send an email using outlook program, we need to add a reference to the dynamic link library for Outlook which is called Microsoft.Office.Interop.Outlook.dll. To do this, firstly go to your solution explorer and click on add a reference. Then, add Microsoft.Office.Interop.Outlook.dll.

Sample code and usage are below.

Usage:

            //using MsOutlook = Microsoft.Office.Interop.Outlook;
            //You must add using statement.

            string[] attachFiles = new string[] { 
                @"C:\test.txt"
            };
            SendMailWithOutlook("Subject1", "This is an example.", "test@csharpexample.com", attachFiles, MailSendType.SendDirect);

Code:

        public enum MailSendType
        {
            SendDirect = 0,
            ShowModal = 1,
            ShowModeless = 2,
        }

        public bool SendMailWithOutlook(string subject, string htmlBody, string recipients, string[] filePaths, MailSendType sendType)
        {
            try
            {
                // create the outlook application.
                MsOutlook.Application outlookApp = new MsOutlook.Application();
                if (outlookApp == null)
                    return false;

                // create a new mail item.
                MsOutlook.MailItem mail = (MsOutlook.MailItem)outlookApp.CreateItem(MsOutlook.OlItemType.olMailItem);

                // set html body. 
                // add the body of the email
                mail.HTMLBody = htmlBody;

                //Add attachments.
                if (filePaths != null)
                {
                    foreach (string file in filePaths)
                    {
                        //attach the file
                        MsOutlook.Attachment oAttach = mail.Attachments.Add(file);
                    }
                }

                mail.Subject = subject;
                mail.To = recipients;
                
                if (sendType == MailSendType.SendDirect)
                    mail.Send();
                else if (sendType == MailSendType.ShowModal)
                    mail.Display(true);
                else if (sendType == MailSendType.ShowModeless)
                    mail.Display(false);

                mail = null;
                outlookApp = null;
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
12 Haz

C# Linq Examples

This examples shows how to use LINQ in your programs, covering the entire range of LINQ functionality.

Example 1: This example finds all elements of an array less than 7.

           int[] allNumbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

            var lowNums1 =
                    from n in allNumbers
                    where n < 7
                    select n;

            //Version 1
            Console.WriteLine("Numbers < 7:");
            foreach (var x in lowNums1)
                Console.WriteLine(x);

            //Version 2
            var lowNums2 = allNumbers.Where(n => n < 7);
            Console.WriteLine("Numbers < 7:");
            foreach (var x in lowNums2)
                Console.WriteLine(x);

            //Both of them writes to the console window like below.
            //
            //Numbers < 7:
            //5
            //4
            //1
            //3
            //6
            //2
            //0

Example2: This example shows the partition a list of words by their first letter with "group by".

            string[] words = { "banana", "apple", "strawberry", "cheese", "pineapple", "book", "angel", "section" };
            var wordGroups1 =
                from w in words
                group w by w[0] into g
                select new { FirstLetter = g.Key, Words = g };

            //Version 1
            foreach (var g in wordGroups1)
            {
                Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter);
                foreach (var w in g.Words)
                    Console.WriteLine(w);
            }

            var wordGroups2 = words.GroupBy(w => w[0], (key, g) => new { FirstLetter = key, Words = g });
            //Version 2
            foreach (var g in wordGroups2)
            {
                Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter);
                foreach (var w in g.Words)
                    Console.WriteLine(w);
            }

            //Both of them writes to the console window like below.
            //
            //Words that start with the letter 'b':
            //banana
            //book
            //Words that start with the letter 'a':
            //apple
            //angel
            //Words that start with the letter 's':
            //strawberry
            //section
            //Words that start with the letter 'c':
            //cheese
            //Words that start with the letter 'p':
            //pineapple           

Example3: This example uses orderby to sort a list of words by length.

            string[] words = { "banana", "apple", "strawberry", "cheese", "pineapple", "book", "angel", "section" };
            var sortedWords1 =
                    from w in words
                    orderby w.Length
                    select w;

            var sortedWords2 = words.OrderBy(w => w.Length);

            //Version 1
            Console.WriteLine("The sorted list of words by length:");
            foreach (var w in sortedWords1)
                Console.WriteLine(w);

            //Version 2
            Console.WriteLine("The sorted list of words by length:");
            foreach (var w in sortedWords2)
                Console.WriteLine(w); 
            
            //Both of them writes to the console window like below.
            //
            //book
            //apple
            //angel
            //banana
            //cheese
            //section
            //pineapple
            //strawberry
12 Haz

C# String Formatting for Double

This example converts the numeric value of this instance to its equivalent string representation, using the specified format.

C# code examples for double formatting:


        /// 
        /// String formatting for double
        /// 
        public void Test1()
        {
            // just two decimal places
            string format1 = string.Format("{0:0.00}", 123.4567);      
            string format2 = string.Format("{0:0.00}", 123.45);        
            string format3 = string.Format("{0:0.00}", 123.0);         
            // format1 = "123.46"
            // format2 = "123.45"
            // format3 = "123.00"


            // max. two decimal places
            string format4 = string.Format("{0:0.##}", 123.4567);      
            string format5 = string.Format("{0:0.##}", 123.4);         
            string format6 = string.Format("{0:0.##}", 123.0);
            // format4 = "123.46"
            // format5 = "123.4"
            // format6 = "123"

            // at least two digits before decimal point
            string format7 = string.Format("{0:00.0}", 123.4567);      
            string format8 = string.Format("{0:00.0}", 12.3456);       
            string format9 = string.Format("{0:00.0}", 1.2345);        
            string format10 = string.Format("{0:00.0}", -1.2345);
            // format7  = "123.5"
            // format8  = "12.3"
            // format9  = "01.2"
            // format10 = "-01.2"
        }

More information about string formatting:
http://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx