zl程序教程

您现在的位置是:首页 >  后端

当前栏目

c#文件的复制,移动,创建(实例代码)

c#实例文件代码 创建 复制 移动
2023-06-13 09:14:50 时间

复制代码代码如下:


protectedvoidPage_Load(objectsender,EventArgse)
{
   if(!Page.IsPostBack)
   {
       this.List();
   }

}
protectedvoidButton1_Click(objectsender,EventArgse)
{
   if(TextBox2.Text=="")
   {
       Response.Write("<scriptlanguage=javascript>alert("文件名错误!");location="javascript:history.go(-1)"</script>");
   }
   else
   {
       try
       {
           stringpath=Server.MapPath("File")+"\\"+TextBox2.Text+DropDownList1.Text;
           FileInfofi=newFileInfo(path);
           if(!fi.Exists)//如果文件不存在
           {
               fi.Create();//创建文件
               Label2.Text="创建成功!文件名:"+TextBox2.Text+DropDownList1.Text;
               List();
           }
       }
       catch(Exceptionerror)
       {
           Response.Write(error.ToString());
       }
   }
}
protectedvoidButton2_Click(objectsender,EventArgse)
{
   try
   {
       stringpath=Server.MapPath("File/")+Session["txt"];
       stringpath2=Server.MapPath("File/")+"复制"+Session["txt"];
       FileInfofi=newFileInfo(path);
       if(fi.Exists)
       {
           fi.CopyTo(path2);//将指定路径文件夹中的文件拷贝到该文件夹中,并将该文件改名
       }
       Label2.Text="复制"+Session["txt"]+"成功!"+"文件为:"+("复制"+Session["txt"].ToString());
       List();
   }
   catch(Exceptionerror)
   {
       Label2.Text="复制文件出错,该文件已被复制过!";
   }
}
protectedvoidButton4_Click(objectsender,EventArgse)
{
   stringpath=Server.MapPath("File/")+ListBox1.SelectedValue.ToString();
   stringpath2=Server.MapPath("file2/")+ListBox1.SelectedValue.ToString();
   FileInfofi=newFileInfo(path);
   FileInfofi2=newFileInfo(path2);
   if(fi.Exists)
   {
       if(!fi2.Exists)
       {
           fi.MoveTo(path2);//将指定文件夹路径中的文件移动到另一个路径中的文件夹
           List();
       }
       else
       {
           Response.Write("<scriptlanguage=javascript>alert("目标文件夹文件已经存在,不能移动改文件!");location="javascript:history.go(-1)"</script>");
       }
   }

}
protectedvoidButton3_Click(objectsender,EventArgse)
{
   if(Session["txt"]==null)
   {
       Label2.Text="请选中文件后在执行删除操作!";
   }
   FileInfofi=newFileInfo(Server.MapPath("File/"+Session["txt"]));
   if(fi.Exists)
   {
       fi.Delete();//删除文件
       Label2.Text="删除"+Session["txt"]+"文件成功!";
       List();
       Session.Clear();//清空变量Session
   }

}
protectedvoidListBox1_SelectedIndexChanged(objectsender,EventArgse)
{
   Session["txt"]=ListBox1.SelectedValue.ToString();
}
publicvoidList()//获取指定文件夹文件名,并绑定ListBox控件显示在页面中
{
   DataTabledt=newDataTable();
   dt.Columns.Add(newDataColumn("Name",typeof(string)));
   stringserverPath=Server.MapPath("File");
   DirectoryInfodir=newDirectoryInfo(serverPath);
   foreach(FileInfofileNameindir.GetFiles())
   {
       DataRowdr=dt.NewRow();
       dr[0]=fileName;
       dt.Rows.Add(dr);
   }
   ListBox1.DataSource=dt;
   ListBox1.DataTextField="Name";
   ListBox1.DataValueField="Name";
   ListBox1.SelectedIndex=0;
   ListBox1.DataBind();
}