Showing posts with label StringBuilder. Show all posts
Showing posts with label StringBuilder. Show all posts

Monday 17 April 2017

Difference between String and StringBuilder in .Net

In this post, I will explain what is the difference between String and StringBuilder in .Net.

In daily practice, most of the people use a string in their code. When someone doing string concatenation again and again it creates those many new instances of strings. But we can overcome this drawback of the string by using StringBuilder. Here I will explain this with an example.

1. String

A string is immutable, Immutable means if you create string object then you cannot modify it and it always creates a new instance of String type in memory. Any operation like insert, replace or append happened to change String, it will discard the old value and it will create a new instance in memory to hold the new value. This creates a performance issue. String belongs to System namespace.

Example - 

string AllNo =  "";

for(int i = 0;  i < 10;  i++)
    AllNo = AllNo + i.ToString();

}

In an example, we are defining a string called AllNo and in a loop, we are concatenating the old string with new to get a string with a list of all No. Whenever we do such things like assigning it again and again. It creates a new instance of a string every time. In this case, it will create 9 more instances of a String.


2. StringBuilder

StringBuilder is mutable. If we create a StringBuilder object then we can perform any operation like insert, replace or append without creating a new instance for every time. Whenever something is changed it will get copied into the same memory areaStringBuilder belongs to System.Text namespace.

By default StringBuilder capacity is only 16 characters! So if we keep on appending more than 16 characters, the original StringBuilder object will be discarded and a new one with double the capacity will be generated internally.

If we know at least an approximate number of characters will be storing in the StringBuilder then it is always a good practice to define StringBuilder with desired capacity.

Example -

StringBuilder AllNo= new StringBuilder(100);

for(int i = 0;  i < 10;  i++)
    AllNo.Append(i.ToString());

}

In an example, we are defining a StringBuilder called AllNo with capacity 100 where we can add all strings. In a loop, we are appending the string with StringBuilder to get a string with a list of all No. Here it won't create a new string, it will return a string instance that will point to the string inside the StringBuilder.

But we cannot use StringBuilder every time. When initializing a StringBuilder, we are going down in performance. Also, many actions that we do with string can't be done with StringBinder. Actually, it should be used mostly for situations as explained in an example.

Wednesday 16 December 2015

ASP.Net - File Uploading

In this post, I will explain how to upload the file on a web server using ASP.Net FileUpload control.

The FileUpload control allows the user to browse for and select the file to be uploaded, providing a browse button and a text box for the filename. Once, the user has selected the filename by browsing, the SaveAs method of the FileUpload control can be called to save the file to the disk.

The basic syntax of FileUpload is: 
<asp:FileUpload ID= "Uploader" runat = "server" />

The FileUpload class is derived from the WebControl class and inherits all its members. Apart from those, the FileUpload class has the following read-only properties:
  
Properties
Description
FileBytes
Returns an array of the bytes in a file to be uploaded.
FileContent
Returns the stream object pointing to the file to be uploaded.
FileName
Returns the name of the file to be uploaded.
HasFile
Specifies whether the control has a file to upload.
PostedFile
Returns a reference to the uploaded file.

The posted file is encapsulated in an object of type HttpPostedFile, which could be accessed through the PostedFile property of the FileUpload class.
The HttpPostedFile class has the following frequently used properties:

Properties
Description
ContentLength
Returns the size of the uploaded file in bytes.
ContentType
Returns the MIME type of the uploaded file.
FileName
Returns the full filename.
InputStream
Returns a stream object pointing to the uploaded file.

Following example demonstrates the FileUpload control and its properties. The form has a FileUpload control along with a save button and a label control for displaying the file name, file type, and file length.
In the design view, the form looks as follows:



The content file code is as given:
<body>
   <form id="form1" runat="server">
      <div>
         <h3> File Upload:</h3>
         <br />
         <asp:FileUpload ID="FileUpload1" runat="server" />
         <br /><br />
         <asp:Button ID="btnsave" runat="server" onclick="btnsave_Click"  Text="Save" style="width:85px" />
         <br /><br />
         <asp:Label ID="lblmessage" runat="server" />
      </div>
   </form>

</body>

The code behind the save button is as given:
protected void btnsave_Click(object sender, EventArgs e)
{
   StringBuilder sb = new StringBuilder();
   if (FileUpload1.HasFile)
   {
      try
      {
         sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName);
         //saving the file
        SaveAs("<c:\\Directory>" + FileUpload1.FileName);
         //Showing the file information
         sb.AppendFormat("<br/> Save As: {0}",  FileUpload1.PostedFile.FileName);
         sb.AppendFormat("<br/> File type: {0}",    FileUpload1.PostedFile.ContentType);
         sb.AppendFormat("<br/> File length: {0}",  FileUpload1.PostedFile.ContentLength);
         sb.AppendFormat("<br/> File name: {0}",  FileUpload1.PostedFile.FileName);
      }catch (Exception ex)
      {
         sb.Append("<br/> Error <br/>");
         sb.AppendFormat("Unable to save file <br/> {0}", ex.Message);
      }
   }
   else
   {
      lblmessage.Text = sb.ToString();
   }
}