String to Base64 [C#]

string to base64

In this post we will look how to convert string to Base64 using C#. .Net provides .ToBase64String() method in System.Convert class that we can use to convert string to base64. It basically converts value of an array of 8-bit unsigned integers to its equivalent String representation consisting of base 64 digits.

Converting string to Base64 is bit tricky. We need to follow some steps mentioned as below

  • 1. We need to convert string to byte array.
  • 2. then we need to use Convert.ToBase64String() to convert byte array to base64 string.

Sample code to convert string to Base64 string [C#]


str ="How to convert string to nase64 in C#"; 
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(str);
// Now convert the byte array to a Base64 string
strBase64 = Convert.ToBase64String(byteArray);

Write to text file [C#]

c# write to text file
File class in System.IO Namespace also contains methods to write contents to text tile. WriteAllText() method to write string to text file. WriteAllLines() method is used to write line by line into text file. And WriteLine() method writes or appends text to the text file with existing contents.
How to write to a text file?
TO write to a text file in file system .net has provided below methods in File class of System.IO namespace:
1.WriteAllText.
2.WriteAllLines.
3.WriteLine.

1.WriteAllText.

WriteAllText method in File class writes one string to the text file

Sample code that shows how to write into to text file[C#]

class WriteFileAllText
{
 static void Main()
 {
  // Example to Write one string into text file.
   string textToWrite = "To write one string into a text file use 
   WriteAllText method, " ;
   System.IO.File.WriteAllText(@"C:\\TextFileFolder\NewTextFile.txt", textToWrite);
 }
}  

2.WriteAllLines.

WriteAllLines method in File class writes contents to a text file line by line.

Sample code that show how to write into a text file line by line[C#]

class WriteFileLines
{
 static void Main()
 {  
  // Example to Write the contents line by line into text file.
  string[] lines = {"Line One", "Line Two", "Line Three"};
  System.IO.File.WriteAllLines(@"C:\TextFileFolder\WriteLines.txt", lines);}
 }  

3.WriteLine.

WriteLine method in File class writes or appends line to a text file that already have some data.

Sample code that show how to append text line into a text file.[C#]

It uses StreamWriter class of System.IO namespace to append line in existing text file
class WriteFileLine
{
static void Main()
{  
 // Append text line to existing file
 System.IO.StreamWriter file = new System.IO.StreamWriter ("C:\TextFileFolder\WriteLines.txt", true)
 {
  file.WriteLine("Line Four");
 }
}

C# Uppercase First Character or Letter

uppercase first letter in string

Some times we need to uppercase the first letter. There are various ways to make first word in uppercase. we will look at some of the ways to uppercase the first letter in strings in the C#. We can take out first character of string from it’s zero index and the using char.ToUpper(str[0]) we can capitalize first character and then concatenate it with remaining string and make string again. Other way to uppercase first character or letter is use .ToCharArray() method and then from array of characters take zero index character make it uppercase and then formulate new string again. Other alternative is to use Substring() method and take characters from position 0 to 1 and capitalize first character and then using substring from 1 position concatenate those strings.

Here we will see how first way will work to uppercase first character or letter of the string using c#.

C# code to uppercases first character

using System;
class Program 
{ 
 static void Main()
 {
  Console.WriteLine(UppercaseFirstLetter("first")); 
 }
 static string UppercaseFirstLetter(string str)
 {
  var  firstChar = str[0];
  var  UpperCaseFirstCharacter =  char.ToUper(firstChar);
  var convertedFirstCharToUpper = UpperCaseFirstCharacter +  str.Substring(1);
  return convertedFirstCharToUpper ;
 }
}


//Result:
//First.

In above code sample for upper case first letter we first take first char as str[0] and using char.ToUpper(str[0]) we Capitalized first character and then concatenated remaining string with first capitalized char and the returns the new string with first letter capitalized.


Second way to Uppercase the First latter of the String:


C# code to uppercases first letter


using System;

class Program
{
 static void Main()
 {
  Console.WriteLine(UppercaseFirstCharacter("first"));    
 }

 static string UppercaseFirstCharacter(string str)
 {
  char[] strArray = str.ToCharArray();
  strArray[0] = char.ToUpper(strArray [0]);
  return new string(strArray);
 }
}


//Result
//First.

In above C# code we have converted input string in to array of characters using .ToCharArray() and then took zero index character and uppercase it and the formed new string with new string constructor to construct string.

Third way to uppercase first character of string using c#

C# code to uppercases first character [C#]


public static string Capitalize(string input)   
{
 str = "first";
 return str.Substring(0, 1).ToUpper() + str.Substring(1);
}


//Result:
//First

In above C# example to uppercase first character of string we used Substring() method. using Substring(0,1) we get first character of string and then we capitalized that character like Substring(0,1).ToUpper() and then we concatenated remaining string from first position onwards to it.

C# string ToLower - Convert string to lowercase

c# string tolower

While writing C# code some times we need a string to be converted to lowercase string, so that the uppercase letters of the string get converted to lowercase letters. This is useful when you need to compare the string with lowercase string. It is good practice to make comparing strings to be convert to uppercase or lowercase if we don’t know how input is coming. We will see how to convert all letters to small case in the string using ToLower function in C#.

C# code that shows how to use ToLower [C#]


using System;
class Program
{
 static void Main()
 {
  string str = "C# STRING LOWERCASE EXAMPLE";
  string upStr = str.ToLower();
  Console.WriteLine(upStr);
 }
}

Result
c# string lowercase example


The ToLower function or method converts all the uppercase characters in the string to lowercase characters, If string contains some lowercase letters or characters it ignores them. We will see how to compare two strings by using lowercase to the input string.

using System;

class Program
{
 static void Main()
 {
  string str = "C# STRING LOWERCASE";
  string upStr = str.ToLower();
  if("c# string lowercase” == upStr)
  Console.WriteLine("Strings are equal.");
 }
}


Result
Strings are equal.

C# string ToUpper - Convert string to uppercase

c# string toupper

In some cases we need to convert lowercase string to uppercase string, so that the lowercase letters of the string get converted  to uppercase letters. We can uppercase string using c# string ToUpper Method This is useful when you need to compare the string with uppercase string. It is good practice to make comparing strings to be convert to uppercase or lowercase if we don’t know how input is coming. We will see how to capitalize all letters in the string using ToUpper function in C#.


C# code that shows how to use ToUpper [C#]


using System;

class Program
{
static void Main()
{
string str = "C# string uppercase example";
string upStr = str.ToUpper();
Console.WriteLine(upStr);
}
}

//Result
//C# STRING UPPERCASE EXAMPLE


The ToUpper function or method converts all the lowercase letters in the string to uppercase letters, If string contains some uppercase letters or characters it ignores them. We will see how to compare two strings by using uppercase the the input string.


using System;

class Program
{
static void Main()
{
string str = "C# string uppercase";
string upStr = str.ToUpper();
if("C# STRING UPPERCASE” == upStr)
Console.WriteLine("Strings are equal.");
}
}

//Result
//Strings are equal.

Some time you may need to just upper case the first latter or character of the string. In that case we can use ToCharArray method and the for first character user char.ToUpper().

C# string

C3 strings
C# string is a object of class String. Value of string is text, which is nothing
but the collections of read-only char Objects. In C# we can do various string operations like
strings splitting, string indexOf, string reverse, string format , we can also use string .ToUpper()
to make string in upper case in C#, also we can use string .ToLower() to make string in
lower case in C#. String also has Trimmimg functions. we can trim the string in
c# using these functions. We will discuss most of these function to perform operations
on string using c#.

C# string is alias for System.String so String and string are equivalent
to each other. The Length property of string shows number of char objects
the string contains. C# string provides lot’s of methods to create and to manipulate,
to compare, to split…etc.


C# string is immutable, means we can not change contents of string once object
is get created. When ever we change the contents of string new object of string
get created. We will see examples of c# string operations and manipulations. Below
samples will show how to make string in upper case in c# and how to make string
in lower case.

1. ToUpper() method is used to convert string in upper case.

Sample code to shows how to convert string to upper case[c#]


string myString = "This is C# string" 
string toUpperString = myString.ToUpper(); 

2. ToLower() method is used to convert string in lower case. Below example
shows how to convert string in lower case:


string myString = "This is C# string"
string tolowerString = myString.ToLower();


3. Trim() method is used to remove all white spaces from both start and end
of the string. 

string myString = " This is C# string "
string trimedString = myString.Trim();

TrimStart() method is used to trim string at start of string and TrimEnd()
is used to trim the string at the end.

TrimStart() C# example:


string myString = " This is C# string ";
string trimedString = myString.TrimStart();

TrimEnd() C# example:


string myString = " This is C# string " ;
string trimedString = myString.TrimEnd(); 

We can strip out specified characters from start of the string or at the end of
the string. Example below shows how to strip out characters from start and end position
TrimSart() C# example:


string myString = " This is C# string "; string 
trimedString = myString.TrimStart(); 
4. Replace() function used to replace string/char from the given string.

string myString = "This is VB string";
string newString = myString.Replace(“VB”, “C#”);


//Above line of code will replace “VB” by “C#”. 

5. Split() function used to split the string by the specified char and stores
it in array. Below code will split string by “,” and will store result in array
of string. Splitting a string into substrings—such as splitting a sentence into
individual words—is a common programming task. The Split() method takes a char array
of delimiters, for example, a space character, and returns an array of substrings.


string myString = "C#,VB,ASP.NET,C++";
string[] splitedString = myString.Split(‘,’); 

6. ToString() method provided by string class converts a value to a string.
Below C# code shows how .ToString() will convert numeric values into string:


int year = 1999;
string msg = year.ToString();

7. Substring() Function finds the specified characters form the string starts from 0 of the string to the used position. Substring functions takes integer parameter, which specifies from what position we need to substring the string. Below Substring sample code shows how to get substring from 8th position till end:


string myString = " This is C# string "
string newSubString = myString.Substring(8);

So result of substring of above code will take string “C# string”. We can also specify
the range from which position to which position we need to get substring.

Example below how Substring() works in c#:


string myString = " This is C# string ";
string newSubString = myString.Substring(8, 2);
Result of above code will be string “C#”. 

8.IndexOf() function is used to find String within string and returns index
position of the string. If specified character or string has not found in string
then it returns -1 index.


string myString = " This is C# string ";
int newSubString = myString.IndexOf (“C#”);
Above code will return 8th index position.

9. ToCharArray() Copies the characters in this instance to a Unicode character
array. We can use then this array to reverse the string.Below is the C# code to
Reverse the string


string myString = "string";
char[] stringArray = myString.ToCharArray();
Array.Reverse(stringArray);
string
newString = new string(stringArray);


Result of above code is “gnirts”.

Concatenate strings:In C# we can "add" two strings of text together
to create one string. The process of adding two strings together is called string
concatenation.


string s1 = "Learn C# ";
string s2 = "Strings";
string newString = s1 + s2;
So newString will hold the concatenated string “Learn C# Strings”.

The @ SymbolThe @ symbol tells the string constructor to ignore
escape characters and line breaks. The following two strings are therefore identical:

string p1 = "\\\\My Documents\\My Files\\";
string p2 = @\\My Documents\My Files\

embed resources like .js, .css or images in c#

C# embedded .js, .css , image resources

In this post we will learn how to embed the resources like javascript file, images, .css files in class libraries. When creating custom controls sometimes we need to provide resources like .js, .css and images along with control or class library assembly.


Below are the step by step example of how to embed .js file as resource and access it using WebResource.axd.

1. In Visual Studio, create a new project with selection as class library project. And Name it as ImageControl.

2. Add references like System.Web, System.Web.UI, System.Web.UI.WebControls..etc which are you think you need for creating controls.

3. Add image file e.g. image1.gif, then right click on image, go to properties and setBuild Action to Embedded Resource. Setting build action to embeddedd resource is important part while embedding resources in controls or in class libraries.

4. If you want javascript file in class library as embedded resource then add .js file e.g. script1.js in the project then add some code to it like:

function ClickMe() 

{
  alert("Hey, I get called by embedded js and I am available through web resources");
} 


5. Now next step is to right click on js file go to properties and set it's Build Action to Embedded Resource. As mentioned above it is important to set action build to embedded resource in controls or in class libraries.

6. Now add one style1.css file in project and follow the same steps to make it embedded resource like right click on css file, goto it's properties and set it's Build Action to Embedded Resource.
e.g.:
body
{
 font-family:Verdana;font-size:x-large;font-weight:bolder;color:Blue;
}

7. In order to access these embedded resource files we can use WebResource. For that we need to do one important thing that we need to add WebResources properties in assemblyinfo.cs of class library or on the class libary page itself just before namespace starts lik:
In AssemblyInfo.cs of the projects properties folder add some think like below at the end of the file.

[assembly: WebResource("ImageControl.Images.image1.gif", "img/gif")]
[assembly: WebResource("ImageControl.Scripts.script1.js", "text/javascript")]
[assembly: WebResource("ImageControl.Css.style1.css", "text/css")]


Here in ImageControl.Scripts.script1.js, ImageControl is the assembly name, Scripts is the folder in which we keep the and after that javascript file name. And is same for other resources.

8. Now to refer these resouces in control we need to do following things.
a. To refer .js file we may do like below in the controls code:

string jsResource = "ImageControl.Scripts.script1.js"; this.Page.ClientScript.RegisterClientScriptResource (this.GetType(), jsResource);

b. To refer to image file we can do like:

Page.ClientScript.GetWebResourceUrl(typeof(ImageControl.ImageHolder), ImageControl.Images.image1.gif"));

c. To refer to .css file we need to do like:
string cssResource = "ImageControl.Css.script1.css";
string cssResourceURL = Page.ClientScript.GetWebResourceUrl(this.GetType(), cssResource);

And in order to add it like

HtmlLink cssLink = new HtmlLink();
 cssLink.Href = cssResourceURL;
 cssLink.Attributes.Add("rel", "stylesheet");
 this.Page.Header.Controls.Add(cssLink);
 

Below id the sample that creates Image control in which we have image, .js and .css as embedded resources. And we are accessin it using WenResource.axd.

using System;
using System.Web.UI.WebControls;
using System.Web.UI;

[assembly: WebResource("ImageControl.Images.image1.gif", "img/gif")]
[assembly: WebResource("ImageControl.Scripts.script1.js", "text/javascript")]
[assembly: WebResource("ImageControl.Css.style1.css", "text/css")]

namespace ImageControl
{
    public class ImageHolder : Image
    {
        protected string _message;
        protected string _toolTip;
        protected bool _showBigIcon = true;
        public ImageHolder()
        {
        }
        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Src,
            Page.ClientScript.GetWebResourceUrl(typeof(ImageControl.
            ImageHolder), "ImageControl.Images.image1.gif"));
            writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "ClickMe()");
            writer.AddAttribute(HtmlTextWriterAttribute.Alt,
            "I am embedded Image and you are watching me from Web Resource");
            base.AddAttributesToRender(writer);
        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            string jsResource = "ImageControl.Scripts.script1.js";
            this.Page.ClientScript.RegisterClientScriptResource(this.GetType(),
            jsResource);
            //To add the CSS file to the custom control
            string cssResource = " ImageControl.Css.style1.css";
            string cssResourceURL = Page.ClientScript.GetWebResourceUrl
            (this.GetType(), cssResource);
            HtmlLink cssLink = new HtmlLink();
            cssLink.Href = cssResourceURL;
            cssLink.Attributes.Add("rel", "stylesheet");
            this.Page.Header.Controls.Add(cssLink);
        }
    }
}


Now to test our Image Control and embedded resources we need to add reference of class library project or dll and need to set below things in Web Project.

1. In web .config add below lines of code :
<pages>
<controls>
<add namespace="ImageControl" assembly="ImageControl" tagPrefix="myImage"/>
</controls>
</pages>
<add assembly="ImageControl" namespace="ImageControl" tagprefix="myImage" />
</controls></pages>
2. And In aspx page
3. < myImage:ImageHolder ID="img1" runat="server"/>

After running code we will get image displayed on page which is embedded and also calls javascript function for embedded .js and will show font that set in embedded .css file on the control.