13 Haz

C# String Formatting for DateTime

These examples shows how to format DateTime using string.Format method.

            DateTime dateTime = DateTime.Now;

            Console.WriteLine(string.Format("{0:yyyy}", dateTime));                 //2014
            Console.WriteLine(string.Format("{0:MMM dd, yyyy}", dateTime));         //Jun 13, 2014
            Console.WriteLine(string.Format("{0:ddd MM, yyyy}", dateTime));         //Fri 06, 2014
            Console.WriteLine(string.Format("{0:dddd MM, yyyy}", dateTime));        //Friday 06, 2014
            Console.WriteLine(string.Format("{0:MMM ddd dd, yyyy}", dateTime));     //Jun Cum 13, 2014
            Console.WriteLine(string.Format("{0:MMMM dddd dd, yyyy}", dateTime));   //June Cuma 13, 2014

            Console.WriteLine(string.Format("{0:yyyy-MM-dd HH:mm:ss}", dateTime));  //2014-06-13 21:05:05
            Console.WriteLine(string.Format("{0:yyyy-MM-dd HH:mm:ss}", dateTime));  //2014-06-13 21:05:05
            Console.WriteLine(string.Format("{0:MM/dd/yy H:mm:ss zzz}", dateTime)); //06.13.14 21:05:05 +03:00

The following table describes the custom date and time format specifiers.

FORMAT SPECIFIER DESCRIPTION
“d” The day of the month, from 1 through 31.
“dd” The day of the month, from 01 through 31.
“ddd” The abbreviated name of the day of the week.
“dddd” The full name of the day of the week.
“f” The tenths of a second in a date and time value.
“ff” The hundredths of a second in a date and time value.
“fff” The milliseconds in a date and time value.
“ffff” The ten thousandths of a second in a date and time value.
“fffff” The hundred thousandths of a second in a date and time value.
“ffffff” The millionths of a second in a date and time value.
“fffffff” The ten millionths of a second in a date and time value.
“F” If non-zero, the tenths of a second in a date and time value.
“FF” If non-zero, the hundredths of a second in a date and time value.
“FFF” If non-zero, the milliseconds in a date and time value.
“FFFF” If non-zero, the ten thousandths of a second in a date and time value.
“FFFFF” If non-zero, the hundred thousandths of a second in a date and time value.
“FFFFFF” If non-zero, the millionths of a second in a date and time value.
“FFFFFFF” If non-zero, the ten millionths of a second in a date and time value.
“g”, “gg” The period or era.
“h” The hour, using a 12-hour clock from 1 to 12.
“hh” The hour, using a 12-hour clock from 01 to 12.
“H” The hour, using a 24-hour clock from 0 to 23.
“HH” The hour, using a 24-hour clock from 00 to 23.
“K” Time zone information.
“m” The minute, from 0 through 59.
“mm” The minute, from 00 through 59.
“M” The month, from 1 through 12.
“MM” The month, from 01 through 12.
“MMM” The abbreviated name of the month.
“MMMM” The full name of the month.
“s” The second, from 0 through 59.
“ss” The second, from 00 through 59.
“t” The first character of the AM/PM designator.
“tt” The AM/PM designator.
“y” The year, from 0 to 99.
“yy” The year, from 00 to 99.
“yyy” The year, with a minimum of three digits.
“yyyy” The year as a four-digit number.
“yyyyy” The year as a five-digit number.
“z” Hours offset from UTC, with no leading zeros.
“zz” Hours offset from UTC, with a leading zero for a single-digit value.
“zzz” Hours and minutes offset from UTC.
“:” The time separator.
“/” The date separator.
“string”
‘string’
Literal string delimiter.
% Defines the following character as a custom format specifier.
\ The escape character.
Any other character The character is copied to the result string unchanged.
13 Haz

Set the GDAL_DATA Environment Variable Programmatically in C#

You can set programmatically to the GDAL_DATA environment variable as follow.

Sample code:


string path = @"C:\gdal\";
SetValueNewVariable("GDAL_DATA", path + "\\data");
SetValueNewVariable("GEOTIFF_CSV", path + "\\data");
SetValueNewVariable("GDAL_DRIVER_PATH", path + "\\gdalplugins");

private static void SetValueNewVariable(string var, string value)
{
    if (System.Environment.GetEnvironmentVariable(var) == null)
       System.Environment.SetEnvironmentVariable(var, value);
}

13 Haz

Zip and Unzip Files Programmatically in C#

There are many zip library which used to be popular. I will show you two of them.(7Zip and .NET ZipArchive)
7-Zip is a open source file archiver with a high compression ratio. Most of the source code is under the GNU LGPL license.
For more information:
http://www.7-zip.org/

You can use 7-zip library for zip and unzip to the files as follow:


            //Firstly, you should set 7z.dll path.
            SevenZipExtractor.SetLibraryPath(@"C:\7z.dll");

            //Test Code:
            string[] filePaths = new string[]
            {
                @"C:\Folder1\file1.jpg",
                @"C:\Folder1\file2.txt",
                @"C:\Folder1\file1.png",
            };
            ZipFiles(filePaths, @"C:\zippedFile2.zip");

            ZipFolder(@"C:\Folder1", @"C:\zippedFile1.zip", "password");
            Unzip(@"C:\zippedFile1.zip", @"C:\Folder2", "password");

Sample methods(using 7-Zip):


        public void ZipFiles(string[] filePaths, string outputFilePath, string password = null)
        {
            var tmp = new SevenZipCompressor();
            tmp.ScanOnlyWritable = true;
            tmp.CompressFilesEncrypted(outputFilePath, password, filePaths);
        }

        public void ZipFolder(string folderPath, string outputFilePath, string password = null)
        {
            var tmp = new SevenZipCompressor();
            tmp.ScanOnlyWritable = true;
            tmp.CompressDirectory(folderPath, outputFilePath, password);
        }

        public void Unzip(string zippedFilePath, string outputFolderPath, string password = null)
        {
            SevenZipExtractor tmp = null;
            if (!string.IsNullOrEmpty(password))
                tmp = new SevenZipExtractor(zippedFilePath, password);
            else
                tmp = new SevenZipExtractor(zippedFilePath);

            tmp.ExtractArchive(outputFolderPath);
        }

In .NET framework 4.5, System.IO.Compression namespace get some new classes that allow you to work with zip files programmatically.
Sample code:


            //Zip files
            ZipArchive zip = ZipFile.Open(filePath, ZipArchiveMode.Create);
            foreach (string file in filePaths)
            {
                zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
            }
            zip.Dispose();

            //Unzip
            ZipFile.CreateFromDirectory(folderPath, zippedFilePath);
            ZipFile.ExtractToDirectory(zippedFilePath, outputFolderPath);
13 Haz

C# Create A New Thread With/Without Parameter

This example shows how to create a new thread in .NET Framework.
First, create a new ThreadStart delegate.
The delegate points to a method that will be executed by the new thread.
Then, call Start method. If you want to pass a parameter to the thread,

Sample Code:


            //start without parameters
            Thread threadWithoutParameter = new Thread(new ThreadStart(delegate()
            {
                //do anything on background
            }));
            threadWithoutParameter.Start();

            //start with parameters
            Thread threadWithParameter = new Thread(new ParameterizedThreadStart(delegate(object obj)
            {
                //do anything on background
            }));
            object param = "Thread parameter";
            threadWithParameter.Start(param);

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