Friday, August 17, 2012

Split and Merge File Example in asp.net

In this example i am showing how to split the file size into more than one file.
(Example: suppose file size is of 200byte and i want to split this file into 2 part 100byte each and save them)

in .aspx page
 <asp:FileUpload ID="FileUpload1" runat="server" />
 <asp:Button ID="btnupload" runat="server" Text="find Byte"
          onclick="btnupload_Click" />
 </p>
 <p>
  No to split :
 <asp:TextBox ID="txtsayno" runat="server"></asp:TextBox>
 </p>
 <p>
 <asp:Button ID="btnsplit" runat="server" onclick="btnsplit_Click" Text="Split" />
 </p>
 
 
in .cs page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
    FileInfo info;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnupload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile && FileUpload1.FileContent.Length > 0)
        { FileUpload1.PostedFile.SaveAs(

Server.MapPath("file/"+FileUpload1.FileName));
         info=new FileInfo(Server.MapPath("file/"+FileUpload1.FileName));
         Session["filename"] = "file/" + FileUpload1.FileName;
            long fileinByte=info.Length;
            Response.Write(fileinByte);
        }
    }
    protected void btnsplit_Click(object sender, EventArgs e)
    {
        flename = new string[100];
        string file = Server.MapPath(Session["filename"].ToString());
        info = new FileInfo(file);

        FileStream fs = new FileStream(file,FileMode.Open,FileAccess.Read);
       int no=Convert.ToInt32(txtsayno.Text);
        int size=Convert.ToInt32(info.Length / no);
        for (int i=0;i<no;i++)
        {
         
        string basename = Path.GetFileNameWithoutExtension(file);
        string ex = Path.GetExtension(file);
        Session["extension"] = ex;
        FileStream outputFile = new FileStream(Path.GetDirectoryName(file) + "\\" + basename + "." + i.ToString().PadLeft(5, Convert.ToChar("0")) + ex + ".tmp", FileMode.Create, FileAccess.Write);
       flename[i] = basename + "." + i.ToString().PadLeft(5, Convert.ToChar("0")) + ex + ".tmp";
       string mergeFolder = Path.GetDirectoryName(file);
                    int bytesRead = 0;
                    byte[] buffer = new byte[size];
                    if ((bytesRead = fs.Read(buffer, 0, size)) > 0)
                    {
                        outputFile.Write(buffer, 0, bytesRead);
                    }
                    outputFile.Close();
                }
                fs.Close();             
        }

    }

To view Merge Example Click: Merge File

No comments:

Post a Comment