Search This Blog

Saturday, 16 July 2016

Copy file from one folder to another in c#

using System.IO;

Copy file from Root Folder to Sub Folder

string fileName = "test.txt";
string sourcePath = @"C:\Test Folder";
string targetPath = @"C:\Test Folder\Sub Folder";

string sourceFile = Path.Combine(sourcePath, fileName);
string destFile = Path.Combine(targetPath, fileName);

if (!Directory.Exists(targetPath))
{
    Directory.CreateDirectory(targetPath);
}

File.Copy(sourceFile, destFile, true);    

Copy file from one folder to another folder

string fileName = "test.txt";
string sourcePath = @"C:\Source Folder";
string targetPath = @"C:\Destination Folder";

string sourceFile = Path.Combine(sourcePath, fileName);
string destFile = Path.Combine(targetPath, fileName);

if (!Directory.Exists(targetPath))
{
    Directory.CreateDirectory(targetPath);
}

File.Copy(sourceFile, destFile, true);    

Copy file from one directories to another directories

string fileName = "test.txt";
string sourcePath = @"C:\Source Folder";
string targetPath = @"D:\Destination Folder";

string sourceFile = Path.Combine(sourcePath, fileName);
string destFile = Path.Combine(targetPath, fileName);

if (!Directory.Exists(targetPath))
{
    Directory.CreateDirectory(targetPath);
}

File.Copy(sourceFile, destFile, true);    

Copy all files from Root Folder to Sub Folder

string sourcePath = @"C:\Test Folder";
string targetPath = @"C:\Test Folder\Sub Folder";

if (!Directory.Exists(targetPath))
{
    Directory.CreateDirectory(targetPath);
}

string[] sourcefiles = Directory.GetFiles(sourcePath);

foreach (string sourcefile in sourcefiles)
{
    string fileName = Path.GetFileName(sourcefile);
    string destFile = Path.Combine(targetPath, fileName);

    File.Copy(sourcefile, destFile, true);
}

Copy all files from one folder to another folder

string sourcePath = @"C:\Source Folder";
string targetPath = @"C:\Destination Folder";

if (!Directory.Exists(targetPath))
{
    Directory.CreateDirectory(targetPath);
}

string[] sourcefiles = Directory.GetFiles(sourcePath);

foreach (string sourcefile in sourcefiles)
{
    string fileName = Path.GetFileName(sourcefile);
    string destFile = Path.Combine(targetPath, fileName);

    File.Copy(sourcefile, destFile, true);
}

Copy all files from one directories to another directories

string sourcePath = @"C:\Source Folder";
string targetPath = @"D:\Destination Folder";

if (!Directory.Exists(targetPath))
{
    Directory.CreateDirectory(targetPath);
}

string[] sourcefiles = Directory.GetFiles(sourcePath);

foreach (string sourcefile in sourcefiles)
{
    string fileName = Path.GetFileName(sourcefile);
    string destFile = Path.Combine(targetPath, fileName);

    File.Copy(sourcefile, destFile, true);
}

Note:-

File.Copy() third parameter is Boolean. By default it’s false. Its true means overwrite the file, if same file exists in destination folder.

Sunday, 3 July 2016

Generate serial number in GridView in ASP.net

<asp:TemplateField HeaderText="Sr.No.">
    <ItemTemplate>
       <%#Container.DataItemIndex+1 %>
    </ItemTemplate>
</asp:TemplateField>

How to create table dynamically in asp.net

Step 1:- Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Demo.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnGenTable" runat="server" Text="Generate Table" OnClick="btnGenTable_Click" />
            <br />
            <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        </div>
    </form>
</body>
</html>

Step 2:- Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo
{
    public partial class Default: System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
            }
            else
            {
                if (Page.IsPostBack)
                {
                    if (Session["DynTable"] != null)
                        PlaceHolder1.Controls.Add(new Literal { Text = Session["DynTable"].ToString() });

                }
            }
        }

        protected DataTable DynamicTable()
        {
            DataTable dt = new DataTable();

            DataRow dr = null;

            dt.Columns.Add(new DataColumn("RowNumber"typeof(string)));

            dt.Columns.Add(new DataColumn("Column1"typeof(string)));

            dt.Columns.Add(new DataColumn("Column2"typeof(string)));

            dt.Columns.Add(new DataColumn("Column3"typeof(string)));

            int totalRow = 5;

            for (int i = 0; i < totalRow; i++)
            {
                dr = dt.NewRow();

                dr["RowNumber"] = i + 1;

                dr["Column1"] = "Row" + i;

                dr["Column2"] = "Row" + i;

                dr["Column3"] = "Row" + i;

                dt.Rows.Add(dr);
            }
            Session["DynTable"] = dt;

            return dt;
        }

        protected void btnGenTable_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<table border=\"1\">");

            DataTable dt = DynamicTable();

            if (dt.Rows.Count > 0)
            {
                // Table Header Name
                sb.AppendLine("<tr>");
                for (int col = 0; col < dt.Columns.Count; col++)
                {
                    sb.AppendLine("<td>" + dt.Columns[col].ColumnName + "</td>");
                }
                sb.AppendLine("</tr>");

                // Table Row details
                for (int row = 0; row < dt.Rows.Count; row++)
                {
                    sb.AppendLine("<tr>");

                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        sb.AppendLine("<td>" + dt.Rows[row][col] + "</td>");
                    }

                    sb.AppendLine("</tr>");
                }
            }

            sb.AppendLine("</table>");

            PlaceHolder1.Controls.Add(new Literal { Text = sb.ToString() });
        }
    }
}

Note:-

Dynamically generated table loss during post back, If page participating multiple post back. 

To solve it, recreate dynamic table during each post back on page load.

Delete existing files in ASP.Net

using System.IO;

string filePath = Request.PhysicalApplicationPath + "Download\\";
DirectoryInfo dirInfo = new DirectoryInfo(filePath);
FileInfo[] fileInfo = dirInfo.GetFiles();

foreach (FileInfo file in fileInfo)
{
    string ext = file.Extension;
    if (ext == ".txt")
    {
        file.Delete();
    }
}

Note:-

Currently deleting only text files.
Delete all files in Download folder.

foreach (FileInfo file in fileInfo)
{
    file.Delete();
}

Delete only specified file in Download folder.

foreach (FileInfo file in fileInfo)
{
    string fileName = file.Name;
    if (fileName == "abc.txt")
    {
        file.Delete();
    }
}

Or

string filePath = Server.MapPath("~/Download") + "abc.txt";
if (File.Exists(filePath))
{
    File.Delete(filePath);
}