Tuesday, 25 August 2015

How to rename File and folders in C#?

File IO operation is backbone of programming, and if we don't know how to rename and file or folder, really is shame for us. If you don't know no worry will giving easy sample code in C# will explore renaming operation using System.IO namespace.


public static void Move(
 string sourceDirName,
 string destDirName

Example Code:
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">

    protected void Page_Load(object sender, EventArgs e)

    protected void btnfolderrename_Click(object sender, EventArgs e)
        string Fromfile = HttpContext.Current.Server.MapPath("oldzip");
        string Tofile = HttpContext.Current.Server.MapPath("oldziprename");
        System.IO.Directory.Move(Fromfile, Tofile);

        Response.Write("Successfully Renamed Folder");
    protected void btnfilerename_Click(object sender, EventArgs e)
        string Fromfile = HttpContext.Current.Server.MapPath("unzipper.aspx");
        string Tofile = HttpContext.Current.Server.MapPath("un-zipper.aspx");
        System.IO.Directory.Move(Fromfile, Tofile);
        Response.Write("Successfully Renamed File");

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Rename File and Folder</title>
<form id="form1" runat="server">

<asp:Button ID="btnfolderrename" runat="server" Text="Rename Folder" OnClick="btnfolderrename_Click" /><asp:Button ID="btnfilerename" runat="server" Text="Rename File" OnClick="btnfilerename_Click" />&nbsp;&nbsp;&nbsp;
Points that we need to keep in minds:
Path name should be full name.
We need to check directory exists or not.  if (Directory.Exists(destinationDir) == false)
Even Directory.Move is easy in use but developer face many problem to accomplish task using this methods. So finally we giving you 100% running bug free code demo that will allow to rename folder and file using vjslib.
Click here for vjslib example to rename a folder or file.