02 Eyl

Convert Image To Byte Array in C#

This example shows how to convert an image into a byte array.

Sample Code:

        public byte[] ImageToByteArray(Image img)
        {
            MemoryStream ms = new MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms.ToArray();
        }

See Also:
Convert Byte Array To Image

02 Eyl

Convert Byte Array To Image in C#

This example shows how to convert a byte array into an image.

Sample Code:

        public Image ByteArrayToImage(byte[] data)
        {
            MemoryStream ms = new MemoryStream(data);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

See Also:
Convert Image To Byte Array

22 Ağu

C# Try-Catch-Finally Usage For Exception Handling

This example shows how to use a try-catch statement for exception handling.

Sample Usage:

            try
            {
                //Do something
            }
            catch(Exception ex)
            {
                //Handle exception
            }
            finally
            {
                //This code is always executed 
            }
22 Ağu

C# Calculate Execution Time

This example shows how much time takes a procedure/function/code. It is useful for micro-benchmarks in code optimization. To do this, We use the Stopwatch class in System.Diagnostics namespace.

Sample Code:

            // Create stopwatch
            Stopwatch stopwatch = new Stopwatch();

            // Begin timing
            stopwatch.Start();

            // Do something
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(10);
            }

            // Stop timing
            stopwatch.Stop();

            // Write result
            Console.WriteLine("Total Time: {0}", stopwatch.ElapsedMilliseconds);
14 Tem

C# Conditional Compilation Directives And Usage

The conditional compilation directives are used to conditionally include or exclude portions of a source file. This example shows how to use of preprocessor directives like “#define”, “#undef”, “#if”, etc. Firstly, you should add your variables above the “using”.

#define Debug // Debugging on
#undef  Trace // Tracing off
            #if Debug
                //To do something
            #endif

            #if Trace
                //To do someting    
            #endif