Wednesday, 26 February 2014

How to Upload a CSV file in C# Windows Form Application

Description:

   In this article, I am going to write C# Windows Form Application code sample to Read or Upload CSV file into Windows Form DataGridView using OpenFileDialog Control to get or browse csv file path and TextFieldParser class from Microsoft.VisualBasic to parse CSV file content.

Summary:


Upload CSV file in C# Windows Form Application - Form Designer

   Here, we have used .NET's OpenFileDialog control to browse CSV file location and DataGridView control to show Imported CSV file data.

Import a CSV file in C# Windows Form Application


//CSVImporter.Designer.cs
-------------------------
partial class CSVImporter
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.tbCSVPath = new System.Windows.Forms.TextBox();
            this.btBrowse = new System.Windows.Forms.Button();
            this.btUpload = new System.Windows.Forms.Button();
            this.dgCSVData = new System.Windows.Forms.DataGridView();
            ((System.ComponentModel.ISupportInitialize)(this.dgCSVData)).BeginInit();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(23, 52);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(50, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "File path:";
            // 
            // tbCSVPath
            // 
            this.tbCSVPath.Location = new System.Drawing.Point(76, 50);
            this.tbCSVPath.Name = "tbCSVPath";
            this.tbCSVPath.Size = new System.Drawing.Size(345, 20);
            this.tbCSVPath.TabIndex = 1;
            // 
            // btBrowse
            // 
            this.btBrowse.Location = new System.Drawing.Point(437, 48);
            this.btBrowse.Name = "btBrowse";
            this.btBrowse.Size = new System.Drawing.Size(101, 23);
            this.btBrowse.TabIndex = 2;
            this.btBrowse.Text = "Browse";
            this.btBrowse.UseVisualStyleBackColor = true;
            this.btBrowse.Click += new System.EventHandler(this.btBrowse_Click);
            // 
            // btUpload
            // 
            this.btUpload.Location = new System.Drawing.Point(76, 76);
            this.btUpload.Name = "btUpload";
            this.btUpload.Size = new System.Drawing.Size(101, 23);
            this.btUpload.TabIndex = 3;
            this.btUpload.Text = "Upload CSV";
            this.btUpload.UseVisualStyleBackColor = true;
            this.btUpload.Click += new System.EventHandler(this.btUpload_Click);
            // 
            // dgCSVData
            // 
            this.dgCSVData.AllowUserToAddRows = false;
            this.dgCSVData.AllowUserToDeleteRows = false;
            this.dgCSVData.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgCSVData.Location = new System.Drawing.Point(26, 129);
            this.dgCSVData.Name = "dgCSVData";
            this.dgCSVData.ReadOnly = true;
            this.dgCSVData.Size = new System.Drawing.Size(512, 129);
            this.dgCSVData.TabIndex = 4;
            // 
            // CSVImporter
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(552, 268);
            this.Controls.Add(this.dgCSVData);
            this.Controls.Add(this.btUpload);
            this.Controls.Add(this.btBrowse);
            this.Controls.Add(this.tbCSVPath);
            this.Controls.Add(this.label1);
            this.Name = "CSVImporter";
            this.Text = "CSVImporter";
            ((System.ComponentModel.ISupportInitialize)(this.dgCSVData)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox tbCSVPath;
        private System.Windows.Forms.Button btBrowse;
        private System.Windows.Forms.Button btUpload;
        private System.Windows.Forms.DataGridView dgCSVData;
    }

Read CSV file in C# Windows Form using TextFieldParser

   We can read data from CSV file in many of custom ways. In this article, we are going to read or import data from CSV file into .NET DataTable by using TextFieldParser. don't try to search this class in C# library because which is not available in C#. TextFieldParser is the Visual basic class. So we need to add reference dll Microsoft.VisualBasic.

  • Right-click the Reference, click Add Reference,select Microsoft.VisualBasic, and click OK button
Import CSV file in ASP.NET
private static DataTable GetDataTableFromCSVFile(string csvfilePath)
{
    DataTable csvData = new DataTable();
    using (TextFieldParser csvReader = new TextFieldParser(csvfilePath))
    {
        csvReader.SetDelimiters(new string[] { "," });
        csvReader.HasFieldsEnclosedInQuotes = true;

        //Read columns from CSV file, remove this line if columns not exits  
        string[] colFields = csvReader.ReadFields();

        foreach (string column in colFields)
        {
            DataColumn datecolumn = new DataColumn(column);
            datecolumn.AllowDBNull = true;
            csvData.Columns.Add(datecolumn);
        }

        while (!csvReader.EndOfData)
        {
            string[] fieldData = csvReader.ReadFields();
            //Making empty value as null
            for (int i = 0; i < fieldData.Length; i++)
            {
                if (fieldData[i] == "")
                {
                    fieldData[i] = null;
                }
            }
            csvData.Rows.Add(fieldData);
        }
    }
    return csvData;
}

Upload CSV file into Windows Form DataGridView - CodeBehind

   This is the C# Windows Form CodeBehind to read or import CSV file into Windows Form GridView. The OpenFileDialog control will help you browse the CSV file location, and here you can also type the CSV file path manually instead of using this OpenFileDialog control to browse CSV path.  Here, we have used filter  "|*.csv" in OpenFileDialog to list only csv files.

Note: Do not forgot to include the Reference Microsoft.VisualBasic to use TextFieldParser class.
//CSVImporter.cs
----------------------------

using System;
using System.Data;
using System.Windows.Forms;
using Microsoft.VisualBasic.FileIO;

namespace WinFormApp
{
    public partial class CSVImporter : Form
    {
        public CSVImporter()
        {
            InitializeComponent();
        }

        private void btBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            // To list only csv files, we need to add this filter
            openFileDialog.Filter = "|*.csv";
            DialogResult result = openFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                tbCSVPath.Text = openFileDialog.FileName;
            }
        }

        private void btUpload_Click(object sender, EventArgs e)
        {
            try
            {
                dgCSVData.DataSource = GetDataTableFromCSVFile(tbCSVPath.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Import CSV File", MessageBoxButtons.OK, 
  MessageBoxIcon.Error);
            }
        }

        private static DataTable GetDataTableFromCSVFile(string csvfilePath)
        {
            DataTable csvData = new DataTable();
            using (TextFieldParser csvReader = new TextFieldParser(csvfilePath))
            {
                csvReader.SetDelimiters(new string[] { "," });
                csvReader.HasFieldsEnclosedInQuotes = true;

                //Read columns from CSV file, remove this line if columns not exits  
                string[] colFields = csvReader.ReadFields();

                foreach (string column in colFields)
                {
                    DataColumn datecolumn = new DataColumn(column);
                    datecolumn.AllowDBNull = true;
                    csvData.Columns.Add(datecolumn);
                }

                while (!csvReader.EndOfData)
                {
                    string[] fieldData = csvReader.ReadFields();
                    //Making empty value as null
                    for (int i = 0; i < fieldData.Length; i++)
                    {
                        if (fieldData[i] == "")
                        {
                            fieldData[i] = null;
                        }
                    }
                    csvData.Rows.Add(fieldData);
                }
            }
            return csvData;
        }       
    }
}

Note: Here, we have assumed the CSV File's first line is column header, so that we are reading columns  by this line:
                string[] colFields = csvReader.ReadFields();
If your CSV file don't have the column header, you can just remove this line.

Output:

 - After compiled the Windows Form project in Visual Studio, run the project by clicking CTRL + F5.
 - Click Browse button to browse CSV file and Upload CSV button to upload CSV file content into DataGridView

How to Read or Import a CSV file in C# Windows Form Application


Thanks,
Morgan
Software Developer

Tuesday, 25 February 2014

Create File using VBScript, Powershell and Command Prompt (cmd)

Description:

In this article, I am going to give code samples to Create File using VBScript, and commands to Create File in Powershell and Command Line (cmd).

Summary:


Create File using VBScript code

   You can create new File easily by using following vbscript, follow the below steps run the VB Script file.

  1. Copy the below example VB Script code and paste it in notepad or a VBScript editor.
  2. Change the value for strDirectory and strFile if you want to give your own path and name otherwise simply leave it.
  3. Save the file with a .vbs extension, for example: CreateFile.vbs
  4. Double-click the vb script file (or Run this file from command window) to Create new File.

Click the following link to get vbscript source code as a file Download CreateFile.vbs
' CreateFile.vbs
' Sample VBScript to Create File .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit
Dim objFSO, objFolder, objShell, objFile
Dim intAnswer, strDirectory, strFile

strDirectory = "C:\Users\Administrator\Desktop"
strFile = "TestVBS.txt"

' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Check that the given folder strDirectory is exists or not
If objFSO.FolderExists(strDirectory) Then
   Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
WScript.Echo "New folder '" & strDirectory &"' Created"
End If

If objFSO.FileExists(strDirectory &"\"& strFile) Then

intAnswer = _
    Msgbox("The file '" & strFile &"' already exists. Do you want to override existing file?",  vbYesNo, "Override File")

If intAnswer = vbYes Then
Set objFile = objFSO.CreateTextFile(strDirectory &"\"& strFile)
      Wscript.Echo "New File '" & strFile &"' created successfully by VBScript"
Else
     ' nothing will happen
End If

Else
Set objFile = objFSO.CreateTextFile(strDirectory &"\"& strFile)
      Wscript.Echo "New File '" & strFile &"' created successfully by VBScript"
End If 

If err.number = vbEmpty then
  ' Create File process completed
Else WScript.echo "VBScript Error: " & err.number
End If

WScript.Quit

' End of VBScript to create a file using VBScript

Create File using VBScript by giving File Name as Dynamic Input

   You can create new File easily by using following vbscript by giving File name as dynamic input, follow the below steps run the VB Script file.

   1. Copy the below example VB Script code and paste it in notepad or a VBScript editor.
   2. Change the value for strDirectory, if you want to give your own path otherwise simply leave it.
   3. Save the file with a .vbs extension, for example: CreateFileByDynamicFileName.vbs
   4. Double-click the vb script file (or Run this file from command window) to Create new File.
   5. Then the input window will ask you enter a file name, enter new file name and click OK to create new file.

Click the following link to get vbscript source code as a file Download CreateFileByDynamicFileName.vbs
' CreateFileByDynamicFileName.vbs
' Sample VBScript to Create File .
' Author: http://www.morgantechspace.com/
' ------------------------------------------------------' 

Option Explicit
Dim objFSO, objFolder, objShell, objFile
Dim intAnswer, strDirectory, strFile

strDirectory = "C:\Users\Administrator\Desktop"

Do
   strFile = InputBox ("Please enter file name")
   If strFile = "" then
      Msgbox "No file name entered"
   end if
Loop Until strFile <> ""


' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Check that the given folder strDirectory is exists or not
If objFSO.FolderExists(strDirectory) Then
   Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
WScript.Echo "New folder '" & strDirectory &"' Created"
End If

If objFSO.FileExists(strDirectory &"\"& strFile) Then

intAnswer = _
    Msgbox("The file '" & strFile &"' already exists. Do you want to override existing file?",  vbYesNo, "Override File")

If intAnswer = vbYes Then
Set objFile = objFSO.CreateTextFile(strDirectory &"\"& strFile)
      Wscript.Echo "New File '" & strFile &"' created successfully by VBScript"
Else
     ' nothing will happen
End If

Else
Set objFile = objFSO.CreateTextFile(strDirectory &"\"& strFile)
      Wscript.Echo "New File '" & strFile &"' created successfully by VBScript"
End If 

If err.number = vbEmpty then
  ' Create File process completed
Else WScript.echo "VBScript Error: " & err.number
End If

WScript.Quit

' End of VBScript to create a file by VBScript

Create File using PowerShell Cmdlet

  You can create new File or Folder using New-Item Cmdlet.

  Use this command to create new file in PowerShell.
 New-Item C:\Users\Administrator\Desktop\testfile.txt -type file
Create File in PowerShell Cmdlet

  Use this command to create new Folder in PowerShell.
 New-Item C:\Users\Administrator\Desktop\testFolder -type directory

Create File from Command Prompt

   There is no direct command to create new File like mkdir for create new folder. here, I am going to create new file by using the command copy con filename.txt.

Follow the steps to create new file from command line inputs:

   1. First we need to change the current location into new location where we want to create new file. we can achieve this by using command CD.
       Type this command and click Enter.
cd "C:\Users\Administrator\Desktop"
 
   2. And type this command, click Enter
copy con testfile.txt
   3. Then, you can type whatever the text you want to write in newly created file.
   4. Then press Ctrl + Z then release both buttons. This will return a symbol ^Z.
   5. Then click Enter to save new file.


Sunday, 23 February 2014

How to Upload CSV file in C# ASP.NET GridView

Description:

   In this article, I am going to write C# ASP.NET code example to Read or Upload CSV file into ASP.NET GridView using ASP FileUpload Control to get file path and TextFieldParser class from Microsoft.VisualBasic to parse CSV File content.

Summary:


Upload CSV file in ASP.NET- HTML markup

   Here, we have used ASP.NET's FileUpload control to browse CSV file location and GridView control to show Imported CSV file data.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Upload CSV File in ASP.NET</title>
    <style type="text/css">
        .gvCSVData
        {
            font-family: Verdana;
            font-size: 10pt;
            font-weight: normal;
            color: black;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1>
            Upload CSV File in ASP.NET</h1>
        <table>
            <tr>
                <td>
                    <asp:FileUpload ID="FileUploadControl" runat="server" />
                    <asp:Button runat="server" ID="btCSVUpload" Text="Upload CSV" 
        OnClick="btCSVUpload_Click" />
                    <asp:Label runat="server" ID="lbStatus" 
Text="CSV Upload status: Select file" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:GridView ID="gvCSVData" CssClass="gvCSVData" runat="server" 
AutoGenerateColumns="True" HeaderStyle-BackColor="#61A6F8"
  HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White">
                    </asp:GridView>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Read CSV file in C# ASP.NET using TextFieldParser

   We can read data from CSV file in many of custom ways. In this article, we are going to read or import data from CSV file into .NET DataTable by using TextFieldParser. don't try to search this class in C# library because which is not available in C#. TextFieldParser is the Visual basic class. So we need to add reference dll Microsoft.VisualBasic.

  • Right-click the Reference, click Add Reference,select Microsoft.VisualBasic, and click OK button
Import CSV file in ASP.NET
private static DataTable GetDataTableFromCSVFile(string csvfilePath)
{
    DataTable csvData = new DataTable();
    using (TextFieldParser csvReader = new TextFieldParser(csvfilePath))
    {
        csvReader.SetDelimiters(new string[] { "," });
        csvReader.HasFieldsEnclosedInQuotes = true;

        //Read columns from CSV file, remove this line if columns not exits  
        string[] colFields = csvReader.ReadFields();

        foreach (string column in colFields)
        {
            DataColumn datecolumn = new DataColumn(column);
            datecolumn.AllowDBNull = true;
            csvData.Columns.Add(datecolumn);
        }

        while (!csvReader.EndOfData)
        {
            string[] fieldData = csvReader.ReadFields();
            //Making empty value as null
            for (int i = 0; i < fieldData.Length; i++)
            {
                if (fieldData[i] == "")
                {
                    fieldData[i] = null;
                }
            }
            csvData.Rows.Add(fieldData);
        }
    }
    return csvData;
}

Upload CSV file into ASP.NET GridView- CodeBehind

   This is the C# ASP.NET CodeBehind to read or import CSV file into ASP.NET GridView. The ASP FileUpload control will give only file name and HttpRequest object. So, we need to read data from HttpRequest object and save CSV file locally, then after uploaded the CSV file content in GridView, we can delete that file.

Note: Do not forgot to include the Reference Microsoft.VisualBasic to use TextFieldParser class.
using System;
using System.Data;
using System.IO;
using Microsoft.VisualBasic.FileIO;

namespace MorganWebProject
{
    public partial class UploadCSV : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btCSVUpload_Click(object sender, EventArgs e)
        {
            if (FileUploadControl.HasFile)
            {
                try
                {
                    string currentPath = Server.MapPath("~/") + 
                                  Path.GetFileName(FileUploadControl.FileName);
                    FileUploadControl.SaveAs(currentPath);

                    gvCSVData.DataSource = GetDataTableFromCSVFile(currentPath);
                    gvCSVData.DataBind();
                    lbStatus.Text = "CSV Upload status: File uploaded!";

                    File.Delete(currentPath);
                }
                catch (Exception ex)
                {
                    lbStatus.Text = @"CSV Upload status: The file could not be uploaded. 
                    The following error has occured: " + ex.Message;
                }
            }
            else
            {
                lbStatus.Text = "CSV Upload status: File not found.";
            }
        }

        private static DataTable GetDataTableFromCSVFile(string csvfilePath)
        {
            DataTable csvData = new DataTable();
            using (TextFieldParser csvReader = new TextFieldParser(csvfilePath))
            {
                csvReader.SetDelimiters(new string[] { "," });
                csvReader.HasFieldsEnclosedInQuotes = true;

                //Read columns from CSV file, remove this line if columns not exits  
                string[] colFields = csvReader.ReadFields();

                foreach (string column in colFields)
                {
                    DataColumn datecolumn = new DataColumn(column);
                    datecolumn.AllowDBNull = true;
                    csvData.Columns.Add(datecolumn);
                }

                while (!csvReader.EndOfData)
                {
                    string[] fieldData = csvReader.ReadFields();
                    //Making empty value as null
                    for (int i = 0; i < fieldData.Length; i++)
                    {
                        if (fieldData[i] == "")
                        {
                            fieldData[i] = null;
                        }
                    }
                    csvData.Rows.Add(fieldData);
                }
            }
            return csvData;
        }
    }
}

Note: Here, we have assumed the CSV File's first line is column header, so that we are reading columns  by this line:
                string[] colFields = csvReader.ReadFields();
If your CSV file don't have the column header, you can just remove this line.

Output:

Read or Import CSV file in ASP.NET

Friday, 21 February 2014

Difference Between UTF-8 and UTF-16

UTF-8 vs UTF-16

In this article, I am going to write key points about what is UTF and difference between UTF-8 and UTF-16.

What is UTF

   UTF stands for Unicode Transformation Format. It is a family of standards for encoding the Unicode character set into its equivalent binary value. UTF was developed so that users have a standardized means of encoding the characters with the minimal amount of space.

UTF-8:

- UTF-8 is a variable-width encoding that can represent every character in the Unicode character set.
- UTF-8 was designed for backward compatibility with ASCII.
- UTF-8 is byte oriented format and therefore has no problems with byte oriented networks or file.
- UTF-8 uses 1 byte at the minimum in encoding the characters.
- UTF-8 is also better in recovering from errors that corrupt portions of the file or stream as it can still decode the next uncorrupted byte.

UTF-16:

- UTF-16 is a character encoding for Unicode capable of encoding 1,112,064 numbers (called code points) in the Unicode code space from 0 to 0x10FFFF.
- UTF-16 is not byte oriented and needs to establish a byte order in order to work with byte oriented networks
- UTF-16 uses 2 bytes at the minimum in encoding the characters.



Thanks,
Morgan
Software Developer

Convert String to Byte Array and Byte Array to String in C#

Description:

In this article, I am going to write C# code to convert Byte Array to String and String to Byte Array by using Encoding.UTF8 and Encoding.ASCII.

Summary:


Convert String to Byte Array in C# using Encoding.UTF8

You can convert String value into byte [] easily by using Encoding.UTF8.
static void Main(string[] args)
    {
        string value = "String value to convert byte Array";

        byte[] byteData = ConvertStringByteArrayUsingEncodingUTF8(value);

        Console.WriteLine(byteData.Length);
    }

    private static byte[] ConvertStringByteArrayUsingEncodingUTF8(string strData)
    {
        byte[] byteData = Encoding.UTF8.GetBytes(strData);

        return byteData;
    }

Convert Byte Array to String in C# using Encoding.UTF8

You can convert Byte Array into String value easily by using Encoding.UTF8.
static void Main(string[] args)
    {
        string value = "String value to convert byte Array";

        byte[] byteData = ConvertStringByteArrayUsingEncodingUTF8(value);

        string value2 = ConvertByteArrayToStringUsingEncodingUTF8(byteData);

        Console.WriteLine(value2);
    }

    private static byte[] ConvertStringByteArrayUsingEncodingUTF8(string strData)
    {
        byte[] byteData = Encoding.UTF8.GetBytes(strData);

        return byteData;
    }

    private static string ConvertByteArrayToStringUsingEncodingUTF8(byte[] byteData)
    {
        string strData = Encoding.UTF8.GetString(byteData);

        return strData;
    }

Convert String to Byte Array in C# using Encoding.ASCII

You can convert String to Byte Array easily by using Encoding.ASCII in C#.

Note: Please note that this convert operation may cause some data loss if you are using some characters that are not in the ASCII character set.
static void Main(string[] args)
    {
        string value = "String value to convert byte Array";

        byte[] byteData = ConvertStringByteArrayUsingASCII(value);

        Console.WriteLine(byteData.Length);
    }

    private static byte[] ConvertStringByteArrayUsingASCII(string strData)
    {
        byte[] byteData = Encoding.ASCII.GetBytes(strData);

        return byteData;
    }

Convert Byte Array to String in C# using ASCIIEncoding.ASCII

You can convert Byte Array into string value easily by using ASCIIEncoding.ASCII in C#.
static void Main(string[] args)
    {
        string value = "String value to convert byte Array";

        byte[] byteData = ConvertStringByteArrayUsingASCII(value);

        string value2 = ConvertByteArrayToStringUsingConvert(byteData);

        Console.WriteLine(value2);
    }

    private static byte[] ConvertStringByteArrayUsingASCII(string strData)
    {
        byte[] byteData = Encoding.ASCII.GetBytes(strData);

        return byteData;
    }

    private static string ConvertByteArrayToStringUsingConvert(byte[] byteData)
    {
        string strData = ASCIIEncoding.ASCII.GetString(byteData);

        return strData;
    }

Thanks,
Morgan
Software Developer

Tuesday, 18 February 2014

Find and List network shares in C# using WMI, Registry and DirectoryEntry

Description:

In this article, I am going to write C# code examples to find and list network shares and share folder's local path in C# using WMI and enumerates network shares without WMI through Registry and Directory Entry in C#.

Summary:


Find and List Network Shares in C# using WMI

   You can get or lists network shares or share folders in C# using WMI API functions, to use WMI API functions, we need to add reference System.Management.
using System.Collections.Generic;
using System.Management;
using System;

namespace EnumerateShares
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Server Name:");
            string serverName = Console.ReadLine();
            Console.WriteLine("-------------");
            List<string> shares = GetNetworkShareFoldersList(serverName);
            foreach (string share in shares)
            {
                Console.WriteLine(share);
                Console.WriteLine("-------------");
            }
            Console.ReadLine();
        }

        public static List<string> GetNetworkShareFoldersList(string serverName)
        {
            List<string> shares = new List<string>();

            // do not use ConnectionOptions to get shares from local machine
            ConnectionOptions connectionOptions = new ConnectionOptions();
            //connectionOptions.Username = @"Domain\Administrator";
            //connectionOptions.Password = "password";
            //connectionOptions.Impersonation = ImpersonationLevel.Impersonate;

            ManagementScope scope = new ManagementScope("\\\\" + serverName + "\\root\\CIMV2",
                                                        connectionOptions);
            scope.Connect();

            ManagementObjectSearcher worker = new ManagementObjectSearcher(scope, 
                               new ObjectQuery("select Name from win32_share"));

            foreach (ManagementObject share in worker.Get())
            {
                shares.Add(share["Name"].ToString());
            }
            return shares;
        }
    }
}

Find and Lists Network Shares and Share's Local Path in C# using WMI

   You can also enumerates or lists network shares and share folder's local path (ex: C path: C:\Shares\FinanceShare) using WMI API functions, to use WMI API functions, we need to add reference System.Management.
using System.Collections.Generic;
using System.Management;
using System;

namespace EnumerateShares
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Server Name:");
            string serverName = Console.ReadLine();
            Console.WriteLine("-------------");
            Dictionary<string,string> shares = GetNetworkShareDetailUsingWMI(serverName);
            foreach (KeyValuePair<string,string> share in shares)
            {
                Console.WriteLine(share.Key + ": " + share.Value);
                Console.WriteLine("-------------");
            }
            Console.ReadLine();
        }

        public static Dictionary<string, string> GetNetworkShareDetailUsingWMI(string serverName)
        {
            Dictionary<string, string> shares = new Dictionary<string, string>();

            // do not use ConnectionOptions to get shares from local machine
            ConnectionOptions connectionOptions = new ConnectionOptions();
            //connectionOptions.Username = @"Domain\Administrator";
            //connectionOptions.Password = "password";
            //connectionOptions.Impersonation = ImpersonationLevel.Impersonate;

            ManagementScope scope = new ManagementScope("\\\\" + serverName + "\\root\\CIMV2",
                                                            connectionOptions);
            scope.Connect();

            ManagementObjectSearcher worker = new ManagementObjectSearcher(scope,
                                        new ObjectQuery("select Name,Path from win32_share"));
            foreach (ManagementObject share in worker.Get())
            {
                shares.Add(share["Name"].ToString(), share["Path"].ToString());
            }
            return shares;
        }
    }
}

Enumerates or Lists Network Shares in C# without WMI though Registry

   The network share folders information are stored in Registry in the following registry path: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Shares. So you can also enumerates or lists network shares and share folder's local path through Registry in C#.
using System.Collections.Generic;
using System;
using System.Linq;
using Microsoft.Win32;

namespace EnumerateShares
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Server Name:");
            string serverName = Console.ReadLine();
            Console.WriteLine("-------------");
            Dictionary<string,string> shares = GetNetworkShareDetailUsingRegistry(serverName);
            foreach (KeyValuePair<string,string> share in shares)
            {
                Console.WriteLine(share.Key + ": " + share.Value);
                Console.WriteLine("-------------");
            }
            Console.ReadLine();
        }

        public static Dictionary<string, string> GetNetworkShareDetailUsingRegistry(string serverName)
        {
            Dictionary<string, string> shares = new Dictionary<string, string>();

            using (RegistryKey reg = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, serverName))
            {
                using (RegistryKey key = reg.OpenSubKey(@"SYSTEM\CurrentControlSet\services\LanmanServer\Shares"))
                {
                    foreach (string shareName in key.GetValueNames())
                    {
                        // Network share local path
                        List<string> keyValues=((string[])key.GetValue(shareName)).ToList();
                        string shareLocalPath = 
                       keyValues.Where(a => a.StartsWith("Path=")).FirstOrDefault().Substring(5);
                        shares.Add(shareName, shareLocalPath);
                    }
                }
            }
                           
            return shares;
        }
    }
}

Find and List Network Shares in C# using DirectoryEntry

   You can also enumerates or lists network shares using DirectoryEntry and IADsFileShare API in C#. To use DirectoryEntry, you need to add reference System.DirectoryServices from .NET library(tab) and to use IADsFileShare, you need to reference ActiveDs from Com library.

Note: You can't get share folder's local path by this method.
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using ActiveDs;

namespace EnumerateShares
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Server Name:");
            string serverName = Console.ReadLine();
            Console.WriteLine("-------------");
            List<string> shares = GetNetworkSharesUsingActiveDSLib(serverName);
            foreach (string share in shares)
            {
                Console.WriteLine(share);
                Console.WriteLine("-------------");
            }
            Console.ReadLine();
        }

        public static List<string> GetNetworkSharesUsingActiveDSLib(string serverName)
        {
            List<string> shares = new List<string>();
            DirectoryEntry dirEntry = new DirectoryEntry("WinNT://" + serverName + "/LanmanServer");
            IADsContainer service = (IADsContainer)dirEntry.NativeObject;
            foreach (var info in service)
            {
                IADsFileShare shareInfo = (IADsFileShare)info;
                if (shareInfo.Class == "FileShare")
                {
                    shares.Add(shareInfo.Name);
                }
            }
            return shares;
        }
    }
}

Thanks,
Morgan
Software Developer Tha

Monday, 17 February 2014

Lock C# function by arguments

Decription:

In this article, I am going to write C# code examples to Lock C# code block based on function's dynamic argument string using lock and String.Intern, lock and custom String Ref table(String.Intern replacement).

Summary:


Lock C# function by Constant String

   You can lock the C# code block by using Constant string like below method.
static void Main(string[] args)
    {
        Thread thread1 = new Thread(ThreadFunction);
        thread1.Start();

        Thread thread2 = new Thread(ThreadFunction);
        thread2.Start();
        Console.ReadLine();
    }

    static void ThreadFunction()
    {
        lock ("lockKey")
        {
            Console.WriteLine(DateTime.Now.ToString());
            Thread.Sleep(10000);
        }
    }

Lock C# code block by dynamic argument using String.Intern

   You can lock the C# function by using function's dynamic arguments. Here, you need to use String.Intern to main same string reference.
static void Main(string[] args)
    {
        string arg = "1";
        Thread thread1 = new Thread(ThreadFunction);
        thread1.Start(arg);

        string arg2 = "1";
        Thread thread2 = new Thread(ThreadFunction);
        thread2.Start(arg2);
        Console.ReadLine();
    }

    static void ThreadFunction(object arg)
    {
        lock (String.Intern(arg.ToString()))
        {
            Console.WriteLine(DateTime.Now.ToString());
            Thread.Sleep(10000);
        }
    }

Lock C# code block by fucntion's arguments using custom String Ref table

   You can lock the C# code block by using function's arguments using custom String Ref table. Here, we have replaced the String.Intern functionality by maintaining custom Dictionary.
    static void Main(string[] args)
    {
        string arg = "1";
        Thread thread1 = new Thread(ThreadFunction);
        thread1.Start(arg);

        string arg2 = "1";
        Thread thread2 = new Thread(ThreadFunction);
        thread2.Start(arg2);
        Console.ReadLine();
    }

    static void ThreadFunction(object arg)
    {
        lock (GetStringReference(arg.ToString()))
        {
            Console.WriteLine(DateTime.Now.ToString());
            Thread.Sleep(10000);
        }
    }

   static List<string> refData = new List<string>();
   static string GetStringReference(string val)
    {
        string retVal = string.Empty;
        for (int i = 0; i < refData.Count; i++)
        {
            if (refData[i].Equals(val))
            {
                retVal = refData[i];
                break;
            }
        }
        if (string.IsNullOrEmpty(retVal))
        {
            refData.Add(val);
            retVal = refData[refData.Count - 1];
        }
        return retVal;
    }


Thanks,
Morgan
Software Developer

Read and Write ini file in c#

Description:

In this article, I am going write C# code example to Read Ini file and Write Ini file using Native Windows API functions ReadPrivateProfileString and WritePrivateProfileString.

Summary:


Ini File structure

  - An INI file consists of various sections, each of one defines various unique keys with an unique value assigned to each key.
  - Sections are declared as a unique word enclosed in square brackets. Spaces enclosed into the square brackets are ignored, but the section must be defined with an unique word.
  - Inside a section, Keys must be unique within the same section, but can have the same key name in different sections. A key is assigned using the equal sign (key = value) .

Sample Ini file:
[Install]
Mode="Advanced"
Port=8080
Path=C:\Program Files\Setup

Read INI file in C# using ReadPrivateProfileString API function

To Read INI file setting in C#, we need to add ReadPrivateProfileString Window API function.
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern uint GetPrivateProfileString(
        string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString,
        uint nSize, string lpFileName);

    static void Main(string[] args)
    {
        string value = ReadINISetting(@"C:\Users\Administrator\Desktop\Setup.ini", 
                                         "Install", "Mode");
        Console.WriteLine(value);
    }
    
    static string ReadINISetting(string iniFilePath, string section, string key)
    {
        var retVal = new StringBuilder(255);

        GetPrivateProfileString(section, key, "", retVal, 255, iniFilePath);

        return retVal.ToString();
    }

Write INI file in C# using WritePrivateProfileString API function

To Write Ini file setting in C#, we need to add WritePrivateProfileString Window API function.
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern bool WritePrivateProfileString(
        string lpAppName, string lpKeyName, string lpString, string lpFileName);

    static void Main(string[] args)
    {
        WriteINISetting(@"C:\Users\Administrator\Desktop\Setup.ini", "Install",
                             "Path", @"C:\Program Files\Setup");
    }

        
    static void WriteINISetting(string iniFilePath, string section, string key,string value)
    {
        WritePrivateProfileString(section, key, value, iniFilePath);
    }

Thanks,
Morgan
Software Developer