Search This Blog

Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Wednesday, February 11, 2015

Create new directory with DirectoryInfo C#

C# > Files > DirectoryInfo Class

Use this class for create, move and enumerating directories and subdirectories. 

Example 

Create new directory

DirectoryInfo directoryInfo = new DirectoryInfo(@"c:\Yourdir");
try
{
if (!directoryInfo.Exists)
       {
              directoryInfo.Create();
       }
}
catch (Exception ex)
{
MessageBox.Show("DirectoryInfo error: {0}", ex.ToString());
}
finally { }





Monday, February 2, 2015

Get Directory Size C#

C# > IO  > FileInfo > Length

Get the size of the file in bytes. 

Example

Get Directory Size C#


public long DirectorySize(DirectoryInfo dir)
{
       long size = 0;
       foreach (FileInfo file in dir.GetFiles())
       {
              size += file.Length;
       }
      foreach (DirectoryInfo directory in dir.GetDirectories())
       {
              size += DirectorySize(directory);
       }
       return size;
 }

DirectoryInfo dir = new DirectoryInfo(@"C:\Temp");
long size = DirectorySize(dir);








Monday, January 19, 2015

C# Capture Screen to PictureBox

C# > Drawing > Capture Screen

Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(printscreen as Image);
graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);
using (MemoryStream s = new MemoryStream())
{
printscreen.Save(s, System.Drawing.Imaging.ImageFormat.Bmp);
       picCapture.Size = new System.Drawing.Size(this.Width, this.Height);
       picCapture.Image = Image.FromStream(s);

}





XmlDocument C# Example

C# > XML > XmlDocument

Represents an XML document.

Example


XmlDocument doc = new XmlDocument();
doc.Load(xmlfile);




NetworkChange Class C#

C# > System.Net > NetworkInformation > NetworkChange

Use this class to receive notification when the IP address of a network interface changes.
Changes can appears when:

  • disconnect network cable
  • out of range of a wireless Local Area Network
  • hardware failure
Events:





    C# NetworkInformation NameSpace

    C# > System.Net > NetworkInformation


    Provides access to network address information and traffic data.

    Classes





    Thursday, January 15, 2015

    ReadAllBytes C# Example

    C# > Files > File Class > ReadAllBytes

    Opens, reads the contents of the file into a byte array, and then closes the file.

    Example

    Read bytes from jpg file and display to PictureBox.

    var bytes = File.ReadAllBytes("D:\\Pics\\1.jpg");
    pictureBox1.Image = Image.FromStream(new System.IO.MemoryStream(bytes));







    C# File Class

    C# > Files > File Class


    Use the File class for:
    • copy, move, rename, create, open, delete to a single file at a time. 
    • get and set file attributes.


    All File methods are static.


    Methods





    Tuesday, January 6, 2015

    IsNumeric equivalent in LINQ example

    C# > LINQ > IsNumeric

    IsNumeric equivalent in LINQ example.

    double value;
    var total = (from DataRow dr in dataTable.Rows
                    where double.TryParse(dr["value"], out value)
                    select Convert.ToDouble(dr["value"])).Sum();





    Wednesday, December 24, 2014

    Dependency Injection C# Example

    C# > PatternsDependency Injection 

    Dependency injection promotes loose coupling of components by passing dependencies to an object rather than having an object instantiate its own dependencies.(http://www.blackwasp.co.uk/DependencyInjection.aspx)

           




    Example

            public interface ITruck
            {
                void Go(double distance);
            }


            public class Truck : ITruck
            {
                public double Consumption{ get; set; }
                public void Go(double distance)
                {
                    double necessary_fuel = Consumption * distance;
                }
            }


            public interface IRoute
            {
                void AddTruck(ITruck dependency);
            }


            public class Route : IRoute
            {
                ITruck _truck;
                public double Distance { get; set; }

                public void AddTruck(ITruck truck)
                {
                    _truck = truck;
                }

                public void TruckGo()
                {
                    _truck.Go(Distance);
                }
            }


                Route route = new Route();
                route.Distance = 100;

                Truck truck = new Truck();
                truck.Consumption = 20;
               
                route.AddTruck(truck);

                route.TruckGo();





    C# System.Security AccessControl

    C# > System.Security > AccessControl

    With AccessControl you can control, access and audit security related actions on securable objects.









      C# > System.Security

      C# > System.Security

      • NET Framework security system
      • provide access to authentication
      • provide crytographic services
      • control access to operations based on policy
      • rights management of application-created content
      Classes





        Friday, December 19, 2014

        Dynamic Type C# Example

        C# > Types > dynamic

        The dynamic enables bypass compile-time type checking. These operations are resolved at run time. 
        Example

        dynamic dyn = 1;
        object obj = 1;

        var dyn_type = dyn.GetType(); // System.Int32
        var obj_type = obj.GetType(); // System.Int32

        dyn = dyn + 1; //Ok
        obj = obj + 1; // Error    1      Operator '+' cannot be applied to operands of type 'object' and 'int'








        Object Type C# Example

        C# > Types > object

         You can assign values of any type to variables of type object

        Example

        object obj;
        obj = 1; 
        string type =  obj.GetType().Name; //Int32
           
        obj = "string";
        type = obj.GetType().Name; //String








        Thursday, December 18, 2014

        Dns Get Host By Name C# Example

        C# > System.Net > Dns

        Retrieves information about a specific host from the Internet Domain Name System (DNS).

        Example

          IPHostEntry hostInfo = Dns.GetHostByName("www.microsoft.com");
          string hostName = hostInfo.HostName;
          IPAddress[] addressList = hostInfo.AddressList;
          foreach (IPAddress ipAddress in addressList)
          {
                      

          }










        Monday, December 15, 2014

        C# System.Net

        C#System.Net

        Provides  programming interface for:

        • network protocols
        • cache policies
        • e-mail
        • network traffic data and network address information
        • networking functionality
        Classes:
        Namespaces










        Assembly Class C# Example

        C# > System > Reflection > Assembly

        Assembly class:

        • load assemblies
        • explore the metadata 
        • find the types contained in assemblies and to create instances of those types.




        Example


        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.Data;
        using System.Drawing;
        using System.Linq;
        using System.Reflection;
        using System.Text;
        using System.Threading.Tasks;
        using System.Windows.Forms;

        namespace WindowsFormsApplication27
        {
            public partial class Form1 : Form
            {
                public Form1()
                {
                    InitializeComponent();
                }

                private void Form1_Load(object sender, EventArgs e)
                {
                    Assembly a = typeof(Form1).Assembly;
                    MessageBox.Show(a.FullName);
                }
            }
        }





        Reflection C#

        C# > System > Reflection

        Reflection provides objects that encapsulate assemblies, modules and types.
        With reflection you can read metadata for finding assemblies, modules and types information at runtime. 
        These objects also can be used to manipulate instances of loaded types.







        Friday, December 5, 2014

        Func C# Example

        C# System Func

        Func is a parameterized type. 

        • accepts any number and kinds of input parameters
        • one type of the return value T
        • stores anonymous methods 
        Example

        1. Func<T, TResult>


        Func<int, int> power = p => p * p;
        int[] numbers = { 1, 2, 3 };
        IEnumerable<int> powers = numbers.Select(power);
        foreach (int p in powers)
             Console.WriteLine(p);