using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
namespace CommonFunction
{
	/// <summary>
	/// OperFile 的摘要说明。
	/// </summary>
	public class OperFile : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.TextBox txtFileInfo;
		protected System.Web.UI.WebControls.Button btnDelFile;
		protected System.Web.UI.WebControls.Button btnCopy;
		protected System.Web.UI.WebControls.Button btnCreate;
		protected System.Web.UI.WebControls.Label Message;
		//测试文件路径
		protected string path = "";
		FileInfo fi1 ;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			path = Server.MapPath("upedFile") + "\\testFile.txt";
			fi1 = new FileInfo(path);
		}

		#region Web 窗体设计器生成的代码
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// 设计器支持所需的方法 - 不要使用代码编辑器修改
		/// 此方法的内容。
		/// </summary>
		private void InitializeComponent()
		{    
			this.btnDelFile.Click += new System.EventHandler(this.btnDelFile_Click);
			this.btnCopy.Click += new System.EventHandler(this.btnCopy_Click);
			this.btnCreate.Click += new System.EventHandler(this.btnCreate_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void btnCreate_Click(object sender, System.EventArgs e)
		{
			if (!fi1.Exists) 
			{
				//创建写入文本文件的流.
				using (StreamWriter sw = fi1.CreateText()) 
				{
					sw.WriteLine("欢迎阅读");
					sw.WriteLine("ASP.NET");
					sw.WriteLine("开发答疑300问");
				}    
			}

			//读取创建的文件.
			using (StreamReader sr = fi1.OpenText()) 
			{
				string s = "";
				while ((s = sr.ReadLine()) != null) 
				{
					txtFileInfo.Text += s+"\r\n";
				}
			}
		}

		private void btnCopy_Click(object sender, System.EventArgs e)
		{
			try 
			{
				string path2 = Server.MapPath("upedFile") + "\\testFile2.txt";
				FileInfo fi2 = new FileInfo(path2);

				//确定目标文件是否存在
				if(fi2.Exists)
				{
					fi2.Delete();
				}

				//复制创建的文件到新的路径.
				fi1.CopyTo(path2);
				Message.Text =path+"拷贝到"+path2;
			}
			catch(Exception error)
			{
				Message.Text = error.ToString();
			}
		}

		private void btnDelFile_Click(object sender, System.EventArgs e)
		{
			try 
			{
				string path2 = Server.MapPath("upedFile") + "\\testFile2.txt";
				FileInfo fi2 = new FileInfo(path2);
				if(fi2.Exists)//如果存在
				{
					//删除新创建的文件.
					fi2.Delete();
					Message.Text =  "成功的删除了路径"+path2+"中的文件";
				}

			} 
			catch(Exception error) 
			{
				Response.Write(error.ToString());
			}
		}
	}
}
