How to Convert Byte Array to String in C#

In .NET, a byte is just a number from 0 to 255 (the numbers that can be represented by eight bits). So, a byte array is just an array of the numbers from 0 to255. At a lower level, an array is a contiguous block of memory, and a byte array is just a representation of that memory in 8-bit blocks.

Let's say you have a Byte[] array loaded from a file and you need to convert it to a String.

1. Encoding's GetString
but you won't be able to get the original bytes back if those bytes have non-ASCII characters

byte[] bytes = { 130, 200, 234, 23 }; // A byte array contains non-ASCII (or non-readable) characters
string Enco = Encoding.UTF8.GetString(bytes); 
byte[] decBytes1 = Encoding.UTF8.GetBytes(Enco);  // decBytes1.Length == 10 !!
// decBytes1 not same as bytes
// Using UTF-8 or other Encoding object will get similar results

2. BitConverter.ToString
The output is a "-" delimited string, but there's no .NET built-in method to convert the string back   to byte array.

string Bitconvo = BitConverter.ToString(bytes);   // 82-C8-EA-17
String[] tempAry = Bitconvo.Split('-');
byte[] decBytes2 = new byte[tempAry.Length];
for (int i = 0; i < tempAry.Length; i++)
    decBytes2[i] = Convert.ToByte(tempAry[i], 16);
// decBytes2 same as bytes

3. Convert.ToBase64String
You can easily convert the output string back to byte array by using Convert.FromBase64String.
Note: The output string could contain '+', '/' and '='. If you want to use the string in a URL, you need to explicitly encode it.

string B64 = Convert.ToBase64String(bytes);  
byte[] decByte3 = Convert.FromBase64String(B64);
// decByte3 same as bytes

4. HttpServerUtility.UrlTokenEncode
You can easily convert the output string back to byte array by using HttpServerUtility.UrlTokenDecode. The output string is already URL friendly! The downside is it needs System.Web assembly if your project is not a web project.

string s3 = Convert.ToBase64String(bytes);  // gsjqFw==
byte[] decByte3 = Convert.FromBase64String(s3);
// decByte3 same as bytes

Credits : combo_ci

How to Make Excel Spreadsheets [.XLS &.XLSX] in C#

How to Make Excel Spreadsheets [.XLS &.XLSX] in C#

There's a library called ExcelLibrary. It's a free, open source library posted on Google Code. It's very simple, small and easy to use. Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data.

ExcelLibrary seems to still only work for the older Excel format (.xls files), but may be adding support in the future for newer 2007/2010 formats. You can also use EPPlus, which works only for Excel 2007/2010 format files (.xlsx files).

Here are a couple links for quick reference:
ExcelLibrary - GNU Lesser GPL
EPPlus - GNU Library General Public License (LGPL)

Here's some example code for ExcelLibrary:

//create new xls file
string file = "C:\\newdoc.xls";
Workbook workbook = new Workbook();
Worksheet worksheet = new Worksheet("First Sheet");
worksheet.Cells[0, 1] = new Cell((short)1);
worksheet.Cells[2, 0] = new Cell(9999999);
worksheet.Cells[3, 3] = new Cell((decimal)3.45);
worksheet.Cells[2, 2] = new Cell("Text string");
worksheet.Cells[2, 4] = new Cell("Second string");
worksheet.Cells[4, 0] = new Cell(32764.5, "#,##0.00");
worksheet.Cells[5, 1] = new Cell(DateTime.Now, @"YYYY\-MM\-DD");
worksheet.Cells.ColumnWidth[0, 1] = 3000;

// open xls file
Workbook book = Workbook.Load(file);
Worksheet sheet = book.Worksheets[0];

 // traverse cells
 foreach (Pair<Pair<int, int>, Cell> cell in sheet.Cells)
     dgvCells[cell.Left.Right, cell.Left.Left].Value = cell.Right.Value;

 // traverse rows by Index
 for (int rowIndex = sheet.Cells.FirstRowIndex;
        rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
     Row row = sheet.Cells.GetRow(rowIndex);
     for (int colIndex = row.FirstColIndex;
        colIndex <= row.LastColIndex; colIndex++)
         Cell cell = row.GetCell(colIndex);

Creating the Excel file is as easy as that. You can also manually create Excel files, but the above functionality is what really impressed me.

Credits : Mike Webb

How to Send SMS in C# Using GSM Modem/Dongle

How to Send SMS in C# Using GSM Modem/Dongle
This is a very simple method to send SMS via GSM Modem so without much explanations let's get into it.

Thing's you'll need :
  • GSM Modem with a SIM
  • Libraries :
If you've installed the Modem software you'll be able find all the libraries needed. Just go to add Reference and add the mentioned libraries (without them this program won't work).

How to Send SMS in C# Using GSM Modem/Dongle

Now go to your form and add control as given below
  • 4 Labels :
    Label1 - Message Body :
    Label2 - Phone Number :
    Label3 - Port :
    Label4 - Modem Not Connected
  • 2 Textboxes :
    Textbox1 - To Phone Number
    Textbox2 - To Message Body
  • 1 ComboBox :
    Combobox1 - To Port :
  • 2 Buttons
    Button1 - Send
    Button2 - Connect
 Arrange your form like this :

How to Send SMS in C# Using GSM Modem/Dongle

 Now let's go to the coding

Namespaces :
 using GsmComm.GsmCommunication;  
 using GsmComm.PduConverter;  
 using GsmComm.Server;  

Add this above Public Form1 :

 private GsmCommMain comm;  

Form1_Load :

Button2_Click :
 if (Combobox1.Text == "")  
         MessageBox.Show("Invalid Port Name");  
       comm = new GsmCommMain(Combobox1.Text, 9600, 150);  
       Cursor.Current = Cursors.Default;  
       bool retry;  
         retry = false;  
           Cursor.Current = Cursors.WaitCursor;  
           MessageBox.Show("Modem Connected Sucessfully");  
           Button2.Enabled = false;  
           label4.Text = "Modem is connected";  
         catch (Exception)  
           Cursor.Current = Cursors.Default;  
           if (MessageBox.Show(this, "GSM Modem is not available", "Check",  
             MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning) == DialogResult.Retry)  
             retry = true;  
           { return; }  
       while (retry);  

Button1_Click :
         Cursor.Current = Cursors.WaitCursor;  
         SmsSubmitPdu pdu;  
           Cursor.Current = Cursors.Default;  
           byte dcs = (byte)DataCodingScheme.GeneralCoding.Alpha7BitDefault;  
           pdu = new SmsSubmitPdu(Textbox2.Text, Textbox1.Text);  
           int times = 1;  
           for (int i = 0; i < times; i++)  
         MessageBox.Show("Message Sent Succesfully","Success",MessageBoxButtons.OK,MessageBoxIcon.Information);  
       catch(Exception ex)  

That's all, Do share your comments.

Credits : Rotich

How To Protect C# Applications From Buffer Overflow Attacks

buffer overflow attack is once the user purposely enters an excessive amount of data in such the way that the program can spill the information across completely different memory locations which can cause bad  behavior like opening another vulnerability for the attack to use.

This works through the utilization of user input. If the information size isn't checked properly before process the information in sure ways in which, it will become prone to a buffer overflow attack.

Protecting from buffer overflow :
we will be using the c-sharp console application(CLI) as an example.

First create a byte array which we will use to store the user input in next, notice that we are giving it a fixed size of 255 bytes.

byte[] byt = new byte[255];

Now we will get some user input.


Now let's convert it to a byte array.


Now set it to our previously declared 'bytes' byte array with a fixed size of 255 bytes...

byt = Encoding.Default.GetBytes(Console.ReadLine());

The vulnerability here is that the user can be inputting a string of 256+ bytes or characters so once converted to bytes, it'll be rather more than the 'bytes'; byte array will handle - a most of 255.

To fix this, we are able to merely check the byte count 1st before setting it to the 'bytes' byte array...
string readLine = Console.ReadLine();
if (Encoding.Default.GetBytes(readLine).Length <= 255) {
byt = Encoding.Default.GetBytes(readLine); 


Now, if the user enters a string that once regenerate to byte is larger than the 'bytes' byte array will handle, it merely will not arrange to set the 'bytes' byte array to the new input.

How To Submit Software, Mobile App and Game On Softpedia

Softpedia Blue Background
Softpedia is a site where you can find computer programs and technology based articles. It's owned by SoftNews NET SRL, a Romanian company. It was launched in 2001. My programs have been reviewed by the Softpedia editors thrice. I submit my programs whenever they are ready to be released.

I have been asked a few times about this(how to submit..). It's pretty easy to submit your programs to Softpedia all you have to do is fill the form fields and submit.

They have different pages to submit for different platforms such as Windows, Linux, Mac etc.

Submit Windows Softpedia

Submit Games and Tools

Submit Mac OS Software

Submit Linux Software

Submit Mobile App

NOTE : you can submit your java programs in any section except Mobile.

Make sure you go to the right page, if you have a PAD file for your software already just fill the PAD form fields and submit if not fill the regular submission forms and submit. Don't forget to give your regular email address they'll send you an email when your program has been published.

Change Your Drive Icon With Drive Icon Changer 1.0

Drive Icon Changer 1.0 is a simple program that helps you to change/modify your Drive's icons with few clicks.

First select the Drive you wish to modify/change the icon, next browse and select an icon(.ICO) from your hard drive. The preview thing shows your a preview of the icon you selected. Finally click 'Change', it doesn't require a restart to effect. An explorer relaunch is enough to see the changes.

  • Administrator rights
  • .NET Framework 2.0(download it from here)
  • Windows XP / Vista / Windows 7 / Windows 7 64 bit / Windows 8 / Windows 8 64 bit
Program Details
  • Developer : SHIM SOFTWARES(Mohamed Shimran)
  • Name : Drive Locker 1.0
  • Size : 763 KB
  • License : Freeware
  • Last Built : December 12th, 2013 
Direct Download -
Mirrors :

How To Draw A Circle Form In C#

 How To Draw A Circle Form In C#
I have seen some controls/components that can change the form into circle.. today I came up with something very simple umm well, it’s done with drawing. You’ll need to add the namespace : using System.Drawing;. We’ll do the drawing in form_load if you want you can do it under a button_click event or something else..

This is the code :

System.Drawing.Drawing2D.GraphicsPath XY = new System.Drawing.Drawing2D.GraphicsPath();
            XY.AddEllipse(0, 0, 300, 300);
            this.Region = new Region(XY);

GraphicsPath() : Initialize a new Graphics Path.
AddEllipse() : Adds a Ellipse to the Graphics Path.
new Region() : Describes a Graphics Shape.

How To Get Environment Variables In VB.NET and C#

Environment Variables are set of values that are used for running special processes or special system files.. for example when you install java or python you must make a new environment variable in order to compile and run java or python programs that's all I know about it. Without wasting anytime let's get into it...

This is a simple code that will show you the environment variables..


        Dim EV As String = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Process Or EnvironmentVariableTarget.Machine)


For C#

'you must add these namespaces 

using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;

'add this code in an event 
string EV = Environment.GetEnvironmentVariable("PATH", 
                EnvironmentVariableTarget.Process | 

The "PATH" defines the environment variable name so if you want to get another ones just change PATH with the variable name.

How To Check If Directory Exists In VB.NET And C#

directory in programming
I have had some hard times in solving this problem not these days but sometime ago when I started programming so I think this would be helpful for anyone who has started programming..

Here's the code to check if the directory exists in VB.NET :

            If System.IO.Directory.GetDirectories("PATH").Length > 0 Then
                MsgBox("directory exists")

            End If
        Catch ex As Exception
        End Try

All you need to do is replace PATH with the directory you want to check... length > 0 identifies if the directory exists.

Here's the code for C# :

                if (System.IO.Directory.GetDirectories("PATH").Length > 0)
                    MessageBox.Show("directory exists");

            catch (Exception ex)

Do the same thing as given for VB.NET code.

How To Use MDI In C#

An MDI(Multiple Document Interface) is a graphical user interface within which multiple windows reside below one parent window. The opposite words of MDI are SDI(Single Document Interface) and TDI(Tabbed Document Interface).

C# - Operators and Expressions

Operators are used to process the data. Expressions are created by combining the operators with variables and constants.

For example:

int number1, number2, sum;
number1 = 10;
number2 = 20;
sum = number1 + number2;

 In the last statement, two variables using the + symbol. The + is a operator also there are many operators in c#.

How To Get Assembly Information In C#

I am sorry guys that I was not able to write articles regularly because I have some issues with my ISP so no internet. I just wanted to write something so I chose something interesting! it's about getting information about the assembly. Just create a console application in C#, import this namespace using System.Reflection; after that go to the main event and add these codes.
 Assembly assembly = Assembly.GetExecutingAssembly();
            AssemblyName assemblyName = assembly.GetName();
            string assembly_information = string.Format("{0}, {1}, {2}, {3}, {4}", assemblyName.Name, assemblyName.VersionCompatibility, assemblyName.ProcessorArchitecture, assemblyName.HashAlgorithm, assemblyName.Version.ToString());
What that does is, first it defines the assembly events and then there’s a string with 5 slots to get the assembly information one by one. You can get more information such as KeyPair, FullName, EscapedCodeBase, ContentType, CultureInfo etc.

Just run the program to get the information and by the way don’t forget to add more slots to the string if you want to get more information about the assembly(I don’t know how it’s called I just call it slot).

How To Force/Prompt Your C# & VB.NET Program To Run As Administrator

If your code will target or access secured files or libraries, then your program needs Administrator Privilege. It's easy to run your program as Administrator, simply you can right click your program and select run as administrator, and in C# & VB.NET theres a XML Manifest that tells the .NET Framework to prompt the user to run the program as Administrator, we can easily configure your program to prompt the user to run the program as administrator.

How to configure your program to prompt the user to run your program as Administrator?

1 : Go to Project(in your visual studio menustrip) and select Add New Item(or simply CTRL+SHIFT+A shortcut to open Add New Item)


2 : Choose Application Manifest File and click add(actually your debug folder has a manifest file but we are adding a new one)

3 : You will find a new file in your Solution Explorer called app.manifest and you will fall into that file automatically lol, inside that file you would have some text(of course XML)








4 : Inside that file find  <requestedExecutionLevel level="asInvoker" uiAccess="false" />

5 : Replace asInvoker with requireAdministrator

6 : That's all

Now whenever you run your program, your program will prompt to run the program as Administrator.

How To Load Array Values Into Listbox & ComboBox In C#

combox tutLast 3 days I have been working on a Library Management System, it's for my college actually it's a group project, but i promised my group members that I will code and design the whole system, by the way i really had lots of problems because this would be my first time doing with a database, also I didn't know how a Library Management System works because I have never been to a Library. Hopefully I am almost done, I am going to meet my group members and ask them to make the Documentation.

Loading Array values into a ComboBox, I had to do it in my Library Management System, I will wrote the same code that I used in my Library Management System.

First we need to create a private Const int(const is a special kind of variable....), a private String Array and set value to them.
private const int Total = 13;
        private String[] genre = new String[Total];
Now coming to the function, we'll create a Function called LoadBookGenres(), and set set values to the arrays, adding to the listbox or combobox, by the way you can still go straightly without creating a new Function like you can set the values for the arrays, and load(sort) the array values to the listbox or the combobox in an event(ex:Form_Load).
private void LoadBookGenres()
            //Assign value into Array
            genre[0] = "Adventure";
            genre[1] = "Animals";
            genre[2] = "Computers & Internet";
            genre[3] = "Biography";
            genre[4] = "Comics";
            genre[5] = "Horror";
            genre[6] = "Sports";
            genre[7] = "Romance";
            genre[8] = "Historical";
            genre[9] = "Music";
            genre[10] = "Religion";
            genre[11] = "Mystery";
            genre[12] = "Other";

            //Sort array and fill listbox with the sorted array
            for (int i = 0; i < genre.Length; i++)
NOTE : Change ListBox1 to your listbox name or your combobox name.
 Remember we set the public const int to 13, always in computer science you should count from 0 and upwards.
Now we just need to call the Function from an event, I called it from Form_load
private void Form1_Load(object sender, EventArgs e)

Here is a picture of this in ListBox.

Here is a picture of this in ComboBox.
I hope this has helped you in someway, Thanks for reading.

How To Make A Round Button In C#

round button for c#
Someone has asked me how to make a round button in c#, if I am right it's really easy to make round button with, I didn't have time to do something really advanced, I made something really simple. All you have to do is just create a new class and add all these codes into your class.
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

class Round : Button
    protected override void OnCreateControl()
        using (var path = new GraphicsPath())
            path.AddEllipse(new Rectangle(2, 2, this.Width - 5, this.Height - 5));
            this.Region = new Region(path);
Just build the project or debug and look for a new tool in your toolbox
toolbox new tool rectangle button
You can add it to your form and use it, by the way I recommend you to use this button also please change the width and other sizes for your needs. 

How To Make A Simple Login System In C#

login form
Everyone knows what a login system is ! so i don't think any explanations are needed . i will come to the main thing , Today we are going to make a simple login system in c# .

You need two text boxes,two labels and two buttons.

Now make the controls look like this on form.form login
Now let's go for login button codes
   //if textbox1 text is admin and textbox2 text is 1234567
            if ((textBox1.Text == "admin") && (textBox2.Text == "1234567"))
                //then show form2
                Form2 nextform = new Form2();
                //if username and password is incorrect show this message box
                MessageBox.Show("Username or Password Invalid");
This is the code for button 2 which is a exit button
Alright we are done ! I hope this is helpful !

How To Hide Internet Explorer Script Errors In VB.NET & C#

internet explorer
I think most of the people hate web browser control script errors in and c# . if you don't know what i mean , look at the picture below i hope you know it.
Internet error script
Okay i will straightly come to the main point ! you just need to add this line of code in form_load 
   Me.WebBrowser1.ScriptErrorsSuppressed = True
'change WebBrowser1 to your webbrowser name' , here is the code for c#
            this.webBrowser1.ScriptErrorsSuppressed = true;
that's a snippet , thanks.

How To : Change Drive Name Or Label In C#

Changing Drive things are pretty easy with kernel32 so what we are going to do is just change the name or label , okay okay i know it's called label and not name most of the times :D . first of all let's design the Form .

Add two text boxes and two labels and a button and make your look like this(if you believe in my UI design)
ui des
Now coming to the coding , hmm we need to add kernel32 to the project so add the namespace using System.Runtime.InteropServices;  , Now import the kernel32.dll to your project by adding these codes under or on top of 
public Form1()
The codes(kernel32)
        static extern long SetVolumeLabelA(string lpRootName, string lpVolumeName);
After that go to your button(rename) click codes and add these
            long lab;
            lab = SetVolumeLabelA(textBox1.Text, textBox2.Text);
Now test your project , if it didn't work for you please let me know by commenting on this post or else contact me via the contact page I hope explanations are not needed for this simple codes , Thank you.

How To : Check Internet Connection In C#

Amm, i think i wrote something about connecting and disconnecting the internet in that's actually a simple matter(process commands) . We are going to use wininet.dll in this tutorial so first of all add this namespace using System.Runtime.InteropServices; after that add this codes after InitializeComponent();  }  
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
        bool IsConnectedToInternet()
            bool a;
            int xs;
            a = InternetGetConnectedState(out xs, 0);
            return a;
What those lines of codes does is , it first adds the dll and then creates a function to use the API,So now to check the state of your internet connection let's use a if condition(;).
            if (IsConnectedToInternet() == true) MessageBox.Show("Internet Is Working");
            if (IsConnectedToInternet() == false) MessageBox.Show("Internet Is Not Working");
Just add those lines for a event to check the internet . Thanks For Reading , Peace.

How To Get Mouse Location(X,Y) In C#

I know this is very basic but i am bored so writing this .
The program we are going to make will show you the mouse cursor location, okay first of all click your form and then go to event (the lightning icon in your properties tab) and then search for MouseMove and just double click on it.
How To Get Mouse Location(X,Y) In C#
After that you will fall into the mouse_move event , go to designer and add two labels and just write down the below codes in MouseMove
label1.Text = "X : "+e.X.ToString();
            label2.Text = "Y : "+e.Y.ToString();

Now debug and try moving your mouse .