13 Haz

C# Generic XML Serialization

This example is the steps to serialize and deserialize an object as XML data. The sample generic class will only serialize “public” properties of a class.

Usage:

            
            CSharpCodeExampleData exData = new CSharpCodeExampleData();
            exData.Name = "Popular C# Examples Web Site";
            exData.Url = "http://www.csharpexamples.com";
            exData.AttributeWillBeIgnore = "This value won't be serialized";
            GenericXMLSerializer<CSharpCodeExampleData> serializer = new GenericXMLSerializer<CSharpCodeExampleData>();

            //Serialize
            string xml = serializer.Serialize(exData);

            //Deserialize
            CSharpCodeExampleData deserilizedObject = serializer.Deserialize(xml);

Generic Code:


    public class GenericXMLSerializer<T>
    {
        /// 
        /// Serializes the specified object and returns the xml value
        /// 
        /// 
        /// 
        public string Serialize(T obj)
        {
            string result = string.Empty;

            System.IO.StringWriter writer = new System.IO.StringWriter();
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
            serializer.Serialize(writer, obj);
            result = writer.ToString();

            return result;
        }

        /// 
        ///  Deserializes the XML content to a specified object
        /// 
        /// 
        /// 
        public T Deserialize(string xml)
        {
            T result = default(T);

            if (!string.IsNullOrEmpty(xml))
            {
                System.IO.TextReader tr = new System.IO.StringReader(xml);
                System.Xml.XmlReader reader = System.Xml.XmlReader.Create(tr);
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

                if (serializer.CanDeserialize(reader))
                    result = (T)serializer.Deserialize(reader);
            }
            return result;
        }
    }

    /// 
    /// class example which will be serialized
    /// 
    public class CSharpCodeExampleData
    {
        [XmlAttribute("Url")]
        public string Url = null;
    
        [XmlAttribute("Name")]
        public string Name = null;

        [XmlIgnore]
        public string AttributeWillBeIgnore = null;
    } 

13 Haz

C# Stream Encryption and Decryption With Multi Algorithm Support

Short information about encryption:
There are many encryption algorithm. They are divided into two as symetric and asymmetric. Symmetric encryption and asymmetric encryption are performed using different processes. Symmetric encryption is performed on streams and is therefore useful to encrypt large amounts of data. Asymmetric encryption is performed on a small number of bytes and is therefore useful only for small amounts of data.

For more information:
http://msdn.microsoft.com/en-us/library/as0w18af%28v=vs.110%29.aspx

This example shows how to encrypt a string or stream data in .NET Framework.
You can encrypt/decrypt all data types(string, file etc.) using sample class.

Usage:

            string plainText = "This is a plain text.";
            CryptoService cryptoService = new CryptoService();
            byte[] data = Encoding.Unicode.GetBytes(plainText);
            byte[] key = Encoding.Unicode.GetBytes("key");
            byte[] cipherData = cryptoService.Encrypt(data, key);

            byte[] decryptedData = cryptoService.Decrypt(cipherData, key);
            string againPlainText = Encoding.Unicode.GetString(decryptedData);

Crypto Code:

    public class CryptoService
    {
        private CipherMode _cipherMode = CipherMode.CFB;
        private PaddingMode _paddingMode = PaddingMode.PKCS7;

        private static readonly byte[] _salt = new byte[] { 0x25, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x12, 0x3c };

        private EncryptionAlgorithm _algorithm = EncryptionAlgorithm.AES;
        public EncryptionAlgorithm Algorithm
        {
            get { return _algorithm; }
            set { _algorithm = value; }
        }
        
        public Stream Encrypt(Stream streamToEncrypt, byte[] key)
        {
            SymmetricAlgorithm algorithm = null;
            if (_algorithm == EncryptionAlgorithm.TripleDES)
                algorithm = new TripleDESCryptoServiceProvider();
            else if (_algorithm == EncryptionAlgorithm.AES)
                algorithm = new RijndaelManaged();
            else
                throw new ApplicationException("Unexpected algorithm type!");

            algorithm.Mode = _cipherMode;
            algorithm.Padding = _paddingMode;

            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(key, _salt, 100);
            algorithm.Key = rfc.GetBytes(algorithm.KeySize / 8);
            algorithm.IV = rfc.GetBytes(algorithm.BlockSize / 8);

            try
            {
                ICryptoTransform encryptor = algorithm.CreateEncryptor();
                using (CryptoStream cryptoStream = new CryptoStream(streamToEncrypt, encryptor, CryptoStreamMode.Read))
                {
                    MemoryStream ms = new MemoryStream();
                    CopyStream(cryptoStream, ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    return ms;
                }
            }
            finally
            {
                algorithm.Clear();
            }
        }

        public Stream Decrypt(Stream streamToDecrypt, byte[] key)
        {
            SymmetricAlgorithm algorithm = null;
            if (_algorithm == EncryptionAlgorithm.TripleDES)
                algorithm = new TripleDESCryptoServiceProvider();
            else if (_algorithm == EncryptionAlgorithm.AES)
                algorithm = new RijndaelManaged();
            else
                throw new ApplicationException("Unexpected algorithm type!");

            algorithm.Mode = _cipherMode;
            algorithm.Padding = _paddingMode;

            Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(key, _salt, 100);
            algorithm.Key = rfc.GetBytes(algorithm.KeySize / 8);
            algorithm.IV = rfc.GetBytes(algorithm.BlockSize / 8);

            try
            {
                ICryptoTransform decryptor = algorithm.CreateDecryptor();
                using (CryptoStream cryptoStream = new CryptoStream(streamToDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    MemoryStream ms = new MemoryStream();
                    CopyStream(cryptoStream, ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    return ms;
                }
            }
            finally
            {
                algorithm.Clear();
            }
        }

        public byte[] Encrypt(byte[] dataToEncrypt, byte[] key)
        {
            MemoryStream ms = new MemoryStream(dataToEncrypt);
            Stream res = Encrypt(ms, key);
            if (res != null)
            {
                byte[] tmp = new byte[res.Length];
                res.Read(tmp, 0, tmp.Length);
                return tmp;
            }

            return null;
        }

        public byte[] Decrypt(byte[] dataToDecrypt, byte[] key)
        {
            MemoryStream ms = new MemoryStream(dataToDecrypt);
            Stream res = Decrypt(ms, key);
            if (res != null)
            {
                byte[] tmp = new byte[res.Length];
                res.Read(tmp, 0, tmp.Length);
                return tmp;
            }

            return null;
        }

        public 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);
            }
        }
    }

    public enum EncryptionAlgorithm
    {
        TripleDES,
        AES,
    }
13 Haz

C# IStream Implementation and IStream Wrapper Class Example

See example/usage below for istream implementation and wrapper. Attachment has two c# files includes MamagedIStream and IStreamWrapper class.

Usage IStreamWrapper and ManagedIStream:

            
            //IStreamWrapper  usage
            IStream iStream = null; // set a new instance
            IStreamWrapper sw = new IStreamWrapper(iStream);
            byte[] data = new byte[1];
            sw.Read(data, 0, 1);


            //ManagedIStream usage
            Stream ms = null; // set a new stream instance
            ManagedIStream managedIStream = new ManagedIStream(ms); // ManagedIStream class implements IStream interface.

Download Files:
CSharpExamples-Managed IStream and IStreamWrapper.RAR

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"