Wednesday 30 January 2013

DateTime Formats C#

DateTime class allows us to get current date,time ,manipulating dates,time spans operations,comparing dates . It has both Static methods and Instance methods.

Get Today's date
 
                        DateTime today = System.DateTime.Today;
                       
                        today.ToString();

                        Default culture for Programs is en-US  LCID 1033.
                        //Output:  month/date/year  midnight time
                          2/1/2013  12:00:00 AM   


Get Day of the Month
           
                    DateTime dt = new DateTime(2013,12,31)
                    dt.Day;
                    //Output: displays Day
                     31  
                 
                   DateTime today = DateTime.Today;

                  today.Day
                    //Output: displays Day
                     31 
                 
                  DateTime.Now.ToString("%d");   

                    
                      //Output: display single digit/two digit date.
                        First Day 1
                        For 10th Day 10

                  DateTime.Now.ToString("dd");   
                    
                      //Output: display two digit date.
                        First Day 01
                        For 10th Day 10
             
Get Day from the Date in Words
           
                    DateTime dt = new DateTime(2013,12,31)
                    dt.DayOfWeek;
                    //Output: displays Day of the week fullname
                     Tuesday
                 
                   DateTime today = DateTime.Today;

                  today.DayOfWeek
                    //Output: displays Day of the Week fullname
                     Tuesday
                 
                  DateTime.Now.ToString("ddd");   

                    
                      //Output: Displays day of the week in short form
                       Fri
                  DateTime.Now.ToString("dddd");   
                    
                      //Output:Displays day of the week in full name
                               Friday.

Get Day from the Date in Number
           
                    DateTime dt = new DateTime(2013,12,31)
                    (int)dt.DayOfWeek;
                    //Output: displays Day of the week number
                     2   2'd day of the week
                 
                   DateTime today = DateTime.Today;

                  (int)today.DayOfWeek
                    //Output: displays Day of the Week fullname
                     Friday   5th day of the week
                 
                   for Sunday  0
                   for Monday 1   etc.,

Get  Month from Date
                                     
                DateTime dtNow = DateTime.Now;
                dt.Month
                  //OUTPUT: Display single digit or two digit Month
                   2

                 DateTime dt = new DateTime(2013,12,31)
                 dt.ToString("%M")
                
                  //OUTPUT: Display single digit or two digit Month

                   12

                 DateTime dt = new DateTime(2013,12,31)
                 dt.ToString("MM")
                
                  //OUTPUT: Display  two digit Month 01-12

                   12
                

                 DateTime dt = new DateTime(2013,12,31)
                 dt.ToString("MMM")
                
                  //OUTPUT: Display  Short name of the Month

                   Dec

                 DateTime dt = new DateTime(2013,12,31)
                 dt.ToString("MMMM")
                
                  //OUTPUT: Display  Full name of the Month

                   December

                 DateTime.Now.ToString("MMMM"); 
                  //Displays full name of the month for current datetime.


                 DateTime.Today.ToString("MMMM"); 
                  //Displays full name of the month for today(above case displays same name).

Get 4-digit Year from Date

                DateTime dtNow = DateTime.Now;
                dt.Year
                  //OUTPUT: Displays 4 digit year
                   2013

                 DateTime dt = new DateTime(2020,12,31)                 dt.ToString("yyy")
                 
                  //  4 yyyy <=> 3 yyy
                  //OUTPUT: Displays  four digit Year

                   2020
                
Get 2-digit Year from Date

                DateTime dtNow = DateTime.Now;
                dt.ToString("%y");
                  //OUTPUT: Displays 2 digit year for year 2013
                   13

                 DateTime dt = new DateTime(2020,12,31)                 dt.ToString("yy")
                 
                  //OUTPUT: Displays  two digit Year
                   20

                 DateTime dt = DateTime.Today
                 dt.ToString("yy")

Get Time in AM/PM format

                    Formats:
                         h --> hour in single digit AM/PM format
                         hh -> hour in two digit  AM/PM format
                         m -->  minute in single digit
                         mm --> two digit format
                         s -->  second in single digit format
                         ss --> Seconds two digit format
                         t ->  AM/PM represents single/first letter i.e A or P
                         tt -> represents  2 chars  AM or PM.

                    DateTime dt = DateTime.Now;
                    dt.ToString("hh:mm:ss tt")                 

                    //OUTPUT: displays hours minutes and Seconds in AM/PM format
                     03:01:11 PM

                      h  hours from  0-9(single digit hour)
                      hh hours from 00-12 (double digit hour)



                     dt.ToString("%h:%m:%s tt")                  

                     //Output: displays hours minutes seconds in single digit format(if applicable)
                     3:1:11 PM


Get Time in 24-hours format

                DateTime dt = DateTime.Now;
                Console.WriteLine(dt.ToString("H:%m:%s"));

              
                //OUTPUT: Time in 24 hours format

                      15:35:35  or 
                      01:01:11 


               Format:  Capital H  or HH or %H  gives two digit 24 hour format
                                       

Monday 28 January 2013

Indexers in C#

Indexers in C#

              Indexers allows class to Index like an array.

Here is an example of Integer Index  as well as String Index.
 
  class IndexersDemo
    {
        int[] arr = new int[100];
        Dictionary<String, String> strArr = new Dictionary<string, string>();
       
        public IndexersDemo()
        {

        }


        public int this[int i]
        {
            get{return arr[i];}
            set{arr[i]=value;}
        }
        public String this[String str]
        {
            get { return strArr[str]; }
            set { strArr[str] = value; }

        }
        void Display()
        {
           
            foreach (int i in arr)
            {
               
                Console.Write(i);
            }

            foreach (KeyValuePair<String, String> strkeyVal in strArr)
            {
                Console.WriteLine("{0} {1}",strkeyVal.Key,strkeyVal.Value);
            }

        }

        public static void Main()
        {
            IndexersDemo id = new IndexersDemo();
            id[0] = 100;
            id[01] = 1000;
            id[02] = 10000;
            id["Hello"] = "World!";
            id["INDIA"] = "Incredible";
            id["UK"] = "Great Britian";
            id["US"] = "United States of America";
            id.Display();
        }
    }

Tags: Indexers in C#,Indexer C# feature,INT indexer in C#,String Indexer in C#

Sunday 27 January 2013

Numeric String sort using LINQ VB.NET/LINQ orderby example


Numeric String sort using LINQ  VB.NET/LINQ orderby example


Sorting integer/decimal Strings using LINQ orderBy

            Dim salaries() As String = {"30,000,000$","24,285,714$","23,125,000$","18,000,000$","15,729,365$","14,940,025$","14,000,000$",
"12,250,000$","10,000,000$","10,000,000$","3,200,000$","2,800,000$","1,875,000$","1,675,000$",
"1,600,000$","528,475$","527,200$","525,000$","523,800$","482,500$","482,000$","480,000$","480,000$"}



            var query = from sal in salaries
                        orderby Decimal.Parse(sal, System.Globalization.NumberStyles.Any)
                        Dim sal As select

            Dim sa As String
            For Each sa In query
                Console.WriteLine(sa)
            Next

OUTPUT

480,000$
480,000$
482,000$
482,500$
523,800$
525,000$
527,200$
528,475$
1,600,000$
1,675,000$
1,875,000$
2,800,000$
3,200,000$
10,000,000$
10,000,000$
12,250,000$
14,000,000$
14,940,025$
15,729,365$
18,000,000$
23,125,000$
24,285,714$
30,000,000$

Tags: How to Sort Numeric Strings in VB.NET, using LINQ to Sort Numeric Strings,LINQ orderby, LINQ to Objects, LINQ Query Expressions, LINQ Select, LINQ Orderby in asp.net,LINQ orderby in Silverlight,LINQ order by in WPF,LINQ orderby in WCF,System.Globalization.NumberStyles.Any

Numeric String sort using LINQ C#

Numeric String sort using LINQ  C#


Sorting integer/decimal Strings using LINQ orderBy

            String[] salaries =
            {
 "30,000,000$","24,285,714$","23,125,000$","18,000,000$","15,729,365$",
"14,940,025$","14,000,000$","12,250,000$","10,000,000$","10,000,000$","3,200,000$",
"2,800,000$","1,875,000$","1,675,000$","1,600,000$","528,475$","527,200$",
"525,000$","523,800$","482,500$","482,000$","480,000$","480,000$"
            };


            var query = from sal in salaries
                        orderby Decimal.Parse(sal, System.Globalization.NumberStyles.Any)
                        select sal;

            foreach (String sa in query)
            {
                Console.WriteLine(sa);
            }
OUTPUT

480,000$
480,000$
482,000$
482,500$
523,800$
525,000$
527,200$
528,475$
1,600,000$
1,675,000$
1,875,000$
2,800,000$
3,200,000$
10,000,000$
10,000,000$
12,250,000$
14,000,000$
14,940,025$
15,729,365$
18,000,000$
23,125,000$
24,285,714$
30,000,000$

Tags: How to Sort Numeric Strings in C#, using LINQ to Sort Numeric Strings,LINQ orderby, LINQ to Objects, LINQ Query Expressions, LINQ Select, LINQ Orderby in asp.net,LINQ orderby in Silverlight,LINQ order by in WPF,LINQ orderby in WCF

Writing xml file using XmlWriter C#

Writing xml file using XmlWriter C#

   Creating  an XML file using XmlWriter part of System.Xml namespace.
Step 1) Create Processing Instruction
Step 2) Create root element called "books" 
Step 3) Create book element
         Step 3.1) Create book title and add it to book
         Step 3.2) Create book price and add it to book
         Step 3.3) Create book publisher and add it to book
                  Step 3.3.1) Create a Authors Node
                  Step 3.3.1.1) Create author node
                              Step 3.3.1.1.1) Create firstname element  add it to author node
                               Step 3.3.1.1.1) Create lastname element       add it to author node    
                   Step 3.3.2) add author node to Authors Node
                  Step   3.3.3)add authors node to book node
Step 4) Add book node to books node
Step 5) Save the XML document                 

   static void CreateXMLusingXMlWriter()
       {
           try
           {
               using (XmlWriter writer = XmlWriter.Create(@"c:\books2.xml"))
               {

                   // writer.WriteProcessingInstruction("xml", "version='1.0'");
                   writer.WriteStartDocument(true);
                   writer.WriteStartElement("books");
                   writer.WriteStartElement("book");
                  
                   writer.WriteStartElement("title");
                   writer.WriteString("C# Programming");
                   writer.WriteEndElement();

                   writer.WriteStartElement("price");
                   writer.WriteString("Rs.67888");
                   writer.WriteEndElement();

                   writer.WriteStartElement("publisher");
                   writer.WriteString("APRESS");
                   writer.WriteEndElement();

                   writer.WriteStartElement("Authors");
                       writer.WriteStartElement("author");
                       writer.WriteStartElement("firstname"); writer.WriteString("jhon"); writer.WriteEndElement();
                       writer.WriteStartElement("lastname"); writer.WriteString("peter"); writer.WriteEndElement();
                       writer.WriteEndElement();
                       writer.WriteEndElement();//authors

                   writer.WriteEndElement();//book

                   writer.WriteEndElement();
                   writer.WriteEndDocument();

               }
           }
           catch (Exception ex)
           {
               Console.WriteLine(ex.Message);
           }
       }
 
 OUTPUT
 
 <?xml version="1.0" encoding="utf-8" standalone="yes"?>
<books>
<book>
      <title>C# Programming</title>
     <price>Rs.67888</price>
     <publisher>APRESS</publisher>
     <Authors>
           <author>
                     <firstname>jhon</firstname>
                     <lastname>peter</lastname>
            </author>
     </Authors>
</book>
</books>
Tags: Writing xml file using XmlWriter C#,Writing an xml file using XmlWriter C#,Creating an XML file using C#, Create XML file using XmlWriter,Create an XML file using XmlWriter, System.Xml.XmlWriter, XMLDocumet.save, Creating an XML in ASP.NET,Creating an XML in WPF. Creating an XML in Windows Forms.

Writing xml file using XmlWriter VB.NET

Writing xml file using XmlWriter VB.NET

   Creating  an XML file using XmlWriter part of System.Xml namespace.
Step 1) Create Processing Instruction
Step 2) Create root element called "books" 
Step 3) Create book element
         Step 3.1) Create book title and add it to book
         Step 3.2) Create book price and add it to book
         Step 3.3) Create book publisher and add it to book
                  Step 3.3.1) Create a Authors Node
                  Step 3.3.1.1) Create author node
                              Step 3.3.1.1.1) Create firstname element  add it to author node
                               Step 3.3.1.1.1) Create lastname element       add it to author node    
                   Step 3.3.2) add author node to Authors Node
                  Step   3.3.3)add authors node to book node
Step 4) Add book node to books node
Step 5) Save the XML document                 

    Shared  Sub CreateXMLusingXMlWriter()
           Try
               Imports (XmlWriter writer = XmlWriter.Create("c:\books2.xml"))
               {

                   ' writer.WriteProcessingInstruction("xml", "version='1.0'");
                   writer.WriteStartDocument(True)
                   writer.WriteStartElement("books")
                   writer.WriteStartElement("book")

                   writer.WriteStartElement("title")
                   writer.WriteString("C# Programming")
                   writer.WriteEndElement()

                   writer.WriteStartElement("price")
                   writer.WriteString("Rs.67888")
                   writer.WriteEndElement()

                   writer.WriteStartElement("publisher")
                   writer.WriteString("APRESS")
                   writer.WriteEndElement()

                   writer.WriteStartElement("Authors")
                       writer.WriteStartElement("author")
                       writer.WriteStartElement("firstname") writer.WriteString("jhon") writer.WriteEndElement()
                       writer.WriteStartElement("lastname") writer.WriteString("peter") writer.WriteEndElement()
                       writer.WriteEndElement()
                       writer.WriteEndElement()'authors

                   writer.WriteEndElement()'book

                   writer.WriteEndElement()
                   writer.WriteEndDocument()

               }
           Catch ex As Exception
               Console.WriteLine(ex.Message)
           End Try
   End Sub


OUTPUT<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<books>
<book>
      <title>C# Programming</title>
     <price>Rs.67888</price>
     <publisher>APRESS</publisher>
     <Authors>
           <author>
                     <firstname>jhon</firstname>
                     <lastname>peter</lastname>
            </author>
     </Authors>
</book>
</books>
Tags: Writing xml file using XmlWriter VB.NET,Writing an xml file using XmlWriter VB.NET,Creating an XML file using VB.NET, Create XML file using XmlWriter,Create an XML file using XmlWriter, System.Xml.XmlWriter, XMLDocumet.save, Creating an XML in ASP.NET,Creating an XML in WPF. Creating an XML in Windows Forms.

Writing xml file using XMLDocument VB.NET

Writing xml file using XMLDocument VB.NET

   Creating  an XML file using XMLDocument part of System.Xml namespace.
Step 1) Create Processing Instruction
Step 2) Create root element called "books" 
Step 3) Create book element
         Step 3.1) Create book title and add it to book
         Step 3.2) Create book price and add it to book
         Step 3.3) Create book publisher and add it to book
                  Step 3.3.1) Create a Authors Node
                  Step 3.3.1.1) Create author node
                              Step 3.3.1.1.1) Create firstname element  add it to author node
                               Step 3.3.1.1.1) Create lastname element       add it to author node    
                   Step 3.3.2) add author node to Authors Node
                  Step   3.3.3)add authors node to book node
Step 4) Add book node to books node
Step 5) Save the XML document                 

  Shared  Sub CreateXMLFile()
            Dim doc As XmlDocument =  New XmlDocument()
            XmlProcessingInstruction xmlPI=
            doc.CreateProcessingInstruction("xml", "version='1.0'")
            doc.AppendChild(xmlPI)

       Dim root As XmlElement = doc.CreateElement("books")
            Dim books As XmlNode =  doc.AppendChild(root)
            Dim book As XmlElement = doc.CreateElement("book")
            'XmlAttribute idattribute =
            book.SetAttribute("id", "1")'doc.CreateAttribute("id");
            'idattribute.Value = "1";
            'book.AppendChild(idattribute);
            Dim title As XmlElement =  doc.CreateElement("title")  title.InnerText  =  "C# Programming"
            book.AppendChild(title)
            Dim Price As XmlElement =  doc.CreateElement("Price")  Price.InnerText  =  "$44.49"
            book.AppendChild(Price)
            Dim Publisher As XmlElement =  doc.CreateElement("Publisher")  Publisher.InnerText  =  "APRESS"
            book.AppendChild(Publisher)

            Dim authors As XmlElement = doc.CreateElement("Authors")
            Dim author As XmlElement = doc.CreateElement("author")
            Dim firstname As XmlElement =  doc.CreateElement("firstname")  firstname.InnerText  =  "jhon"
            Dim lastname As XmlElement =  doc.CreateElement("lastname")  lastname.InnerText  =  "peter"
            Dim author.AppendChildCType(As author.AppendChild(firstname), lastname)
            authors.AppendChild(author)

            book.AppendChild(authors)

            books.AppendChild(book)

             doc.Save("c:\books.xml")
  End Sub

OUTPUT
<?xml version='1.0'?>
<books>
  <book id="1">
    <title>C# Programming</title>
    <Price>$44.49</Price>
    <Publisher>APRESS</Publisher>
    <Authors>
      <author>
        <firstname>jhon</firstname>
        <lastname>peter</lastname>
      </author>
    </Authors>
  </book>
</books>

Tags: Writing xml file using XMLDocument VB.NET,Writing an xml file using XMLDocument VB.NET,Creating an XML file using VB.NET, Create XML file using XMLDocument, Create an XML file using XMLDocument,System.Xml.XMLDocument, XMLDocumet.save, Creating an XML in ASP.NET,Creating an XML in WPF. Creating an XML in Windows Forms.

Writing xml file using XMLDocument c#

Writing xml file using XMLDocument c#

   Creating  an XML file using XMLDocument part of System.Xml namespace.
Step 1) Create Processing Instruction
Step 2) Create root element called "books" 
Step 3) Create book element
         Step 3.1) Create book title and add it to book
         Step 3.2) Create book price and add it to book
         Step 3.3) Create book publisher and add it to book
                  Step 3.3.1) Create a Authors Node
                  Step 3.3.1.1) Create author node
                              Step 3.3.1.1.1) Create firstname element  add it to author node
                               Step 3.3.1.1.1) Create lastname element       add it to author node    
                   Step 3.3.2) add author node to Authors Node
                  Step   3.3.3)add authors node to book node
Step 4) Add book node to books node
Step 5) Save the XML document                 

    static void CreateXMLFile()
        {
            XmlDocument doc = new XmlDocument();
            XmlProcessingInstruction xmlPI=
            doc.CreateProcessingInstruction("xml", "version='1.0'");
            doc.AppendChild(xmlPI);
           
       XmlElement root=doc.CreateElement("books");
            XmlNode books = doc.AppendChild(root);
            XmlElement book=doc.CreateElement("book");
            //XmlAttribute idattribute =
            book.SetAttribute("id", "1");//doc.CreateAttribute("id");
            //idattribute.Value = "1";
            //book.AppendChild(idattribute);
            XmlElement title = doc.CreateElement("title"); title.InnerText = "C# Programming";
            book.AppendChild(title);
            XmlElement Price = doc.CreateElement("Price"); Price.InnerText = "$44.49";
            book.AppendChild(Price);
            XmlElement Publisher = doc.CreateElement("Publisher"); Publisher.InnerText = "APRESS";
            book.AppendChild(Publisher);

            XmlElement authors=doc.CreateElement("Authors");
            XmlElement author=doc.CreateElement("author");
            XmlElement firstname = doc.CreateElement("firstname"); firstname.InnerText = "jhon";
            XmlElement lastname = doc.CreateElement("lastname"); lastname.InnerText = "peter";
            author.AppendChild(firstname); author.AppendChild(lastname);
            authors.AppendChild(author);

            book.AppendChild(authors);

            books.AppendChild(book);

             doc.Save(@"c:\books.xml");
        }

OUTPUT

<?xml version='1.0'?>
<books>
  <book id="1">
    <title>C# Programming</title>
    <Price>$44.49</Price>
    <Publisher>APRESS</Publisher>
    <Authors>
      <author>
        <firstname>jhon</firstname>
        <lastname>peter</lastname>
      </author>
    </Authors>
  </book>
</books>

Tags: Writing xml file using XMLDocument c#,Writing an xml file using XMLDocument c#,Creating an XML file using C#, Create XML file using XMLDocument, Create an XML file using XMLDocument,System.Xml.XMLDocument, XMLDocumet.save, Creating an XML in ASP.NET,Creating an XML in WPF. Creating an XML in Windows Forms.

Get operating system name using c#/VB.NET

Get operating system name using c#/Vb.NET

Add namespace Microsoft.Win32
        void GetWindowsPlatform()
        {
            OperatingSystem os=System.Environment.OSVersion;
            Console.WriteLine("OS Platform: {0}",os.Platform);
            Console.WriteLine("OS Service Pack: {0}",os.ServicePack);
            Console.WriteLine("OS Version: {0}",os.VersionString);
            String subKey = @"SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion";
            RegistryKey key = Registry.LocalMachine;
            RegistryKey skey = key.OpenSubKey(subKey);
            Console.WriteLine("OS Name: {0}",skey.GetValue("ProductName"));
}
 for getting  Operating System Friendly Name for 32-bit & 64-bit  registry keys

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion  -->32-bit

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion -->64-bit

OUTPUT

OS Platform: Win32NT
OS Service Pack: Service Pack 1
OS Version: Microsoft Windows NT 6.1.7601 Service Pack 1
OS Name: Windows 7 Home Basic
 

Tags: get OS name,get OS friendly name,get OS version,get OS Service Pack,Get OS Platform,How to get OS Platform,How to get OS Version ,How to get OS Service Pack,get Operating System  name,get Operating System  friendly name,get Operating System  version,get Operating System  Service Pack,Get Operating System  Platform,How to get Operating System  Platform,How to get Operating System  Version ,How to get Operating System  Service Pack,

 

Get .NET CLR Version C#/VB.NET

Get .NET CLR Version C#

This example explains how to get CLR version your program is running ON

            Console.WriteLine("Build={0}",Environment.Version.Build);
            Console.WriteLine("Major={0}",Environment.Version.Major);
            Console.WriteLine("MajorRevision={0}",Environment.Version.MajorRevision);
            Console.WriteLine("Minor={0}",Environment.Version.Minor);
            Console.WriteLine("MinorRevision={0}",Environment.Version.MinorRevision);
            Console.WriteLine("Revision={0}",Environment.Version.Revision);
            Console.WriteLine("CLR VERSION={0}",Environment.Version);

OUTPUT

Major=4
MajorRevision=0
Minor=0
MinorRevision=17929
Revision=17929
CLR VERSION=4.0.30319.17929

Tags:Get .NET CLR Version C#,GET C# CLR VERSION,get asp.net CLR version,get WPF clr version.get Silverlight clr version. get vb.net clr version,

Saturday 26 January 2013

Delete a Directory or Folder in VB.NET

Delete a Directory or Folder in VB.NET


Deleting a   folder/Directory in VB.NET Can be done by 2 ways.
1.Static Method of Directory class Delete
2.Instance method of DirectoryInfo Delete

Before that Call  using System.IO;

Calling

DeleteDirectory("c:\personal");

 

Method1   - Directory Static method 

Shared  Sub DeleteFolder(ByVal src As String)
     Try

        'true means all sub directories with content will be deleted

        'false : Only Empty Directory will be deleted.

        ' false: If directory has content recursion set to false exception will be thrown

         Directory.Delete(src,True)
     Catch ex As Exception
         Console.WriteLine(ex.Message)
     End Try
 End Sub
 

Method 2 - DirectoryInfo Instance Method

  Shared  Sub DeleteFolder(ByVal src As String)
     Try

        'true means all sub directories with content will be deleted

        'false : Only Empty Directory will be deleted.

        ' false: If directory has content recursion set to false exception will be thrown

         Dim dInfo As DirectoryInfo =  New DirectoryInfo(src)
         dInfo.Delete(True)
     Catch ex As Exception
         Console.WriteLine(ex.Message)
     End Try
  End Sub

 

 

  • Could not find a part of the path 'c:\mypersonal'. If directory mypersonal does not exists.
  • The directory is not empty.  if directory has files/folders and recursion set to false.

Tags: Delete directory in VB.NET,Delete Folder in VB.NET, Delete all files and folders in VB.NET, Directory.Delete,DirectoryInfo.Delete,System.IO. Delete Directory with files,Delete Directory with content VB.NET,Delete Directory recursively.

Delete a Directory or Folder in C#

Delete a Directory or Folder in C#



Deleting a   folder/Directory in C# Can be done by 2 ways.
1.Static Method of Directory class Delete
2.Instance method of DirectoryInfo Delete

Before that Call  using System.IO;

Calling

DeleteDirectory(@"c:\personal");

 

Method1   - Directory Static method 

static void DeleteFolder(String src)
 {
     try
     {
        //true means all sub directories with content will be deleted
        //false : Only Empty Directory will be deleted.
        // false: If directory has content recursion set to false exception will be thrown
         Directory.Delete(src,true);

     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }

 

Method 2 - DirectoryInfo Instance Method

 static void DeleteFolder(String src)
 {
     try
     {
        //true means all sub directories with content will be deleted
        //false : Only Empty Directory will be deleted.
        // false: If directory has content recursion set to false exception will be thrown

         DirectoryInfo dInfo = new DirectoryInfo(src);
         dInfo.Delete(true);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
 }

 

 

  • Could not find a part of the path 'c:\mypersonal'. If directory mypersonal does not exists.
  • The directory is not empty.  if directory has files/folders and recursion set to false.

Tags: Delete directory in C#,Delete Folder in C#, Delete all files and folders in C#, Directory.Delete,DirectoryInfo.Delete,System.IO. Delete Directory with files,Delete Directory with content C#,Delete Directory recursively.

Rename a Directory or folder in VB.NET

Rename a Directory or folder in Vb.NET


Rename a folder in VB.NET/Move a folder in Vb.NET Can be done by 2 ways.
1.Static Method of Directory class Move
2.Instance method of DirectoryInfo MoveTo
Note: Moving a folder content to different Volume  throws an exception.
for this  user must copy all files to different volume/network drive/USB etc., then delete Source Content. Pls see other other articles .
Before that Call  imports System.IO;
 

Calling

Move_or_Rename_Directory("c:\personal", "c:\mypersonal");

 

Method1   - Directory Static method 

Shared  Sub Move_or_Rename_Directory(ByVal srcDir As String, ByVal destDir As String)
        Try
            Directory.Move(srcDir, destDir)
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
 End Sub
    }

Method 2 - DirectoryInfo Instance Method 


  Shared  Sub Move_or_Rename_Directory(ByVal srcDir As String, ByVal destDir As String)
        Try
            Dim dInfo As DirectoryInfo =  New DirectoryInfo(srcDir)
            dInfo.MoveTo(destDir)

        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
  End Sub
   
   //output
check 
C:\mypersonal
user may get following exceptions
  • Could not find a part of the path 'c:\personal'. (if source folder "personal" does not exists).
  • Calling Move on different Volumes may result. i.e C:\ to D:\(vice versa) "Source and destination path must have identical roots. Move will not work across
     volumes
    "
Tags: Move a directory in VB.NET,Move a folder in VB.NET,Move a directory Structure to Different Location,Move a folder Structure to Different Location VB.NET, Move Directory with Content to Different Folder, Move all content to Different Folder,Move content to another name,Move all content to Different Directory, Rename a Directory VB.NET,Rename a Folder in VB.NET,How to rename a folder in VB.NET,Directory.Move,DirectoryInfo.MoveTo,System.IO,Move a folder in the same volume VB.NET