⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 default.aspx.cs

📁 这个源代码是我在没有参考任何现成的代码的情况下一个字母一个字母敲进去的.目前实现了创建文件,读写文件的操作,暂时不支持子目录、长文件名、文件删除、重命名等操作。
💻 CS
字号:
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.Security;
using System.Xml;

namespace FTP
{
	public class MainFileSystemViewer : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.TextBox NewFileText;
		protected System.Web.UI.WebControls.TextBox NewFolderText;
		protected System.Web.UI.WebControls.Button NewFolderBtn;
		protected System.Web.UI.WebControls.Button NewFileBtn;
		protected System.Web.UI.WebControls.Button UploadBtn;
		protected System.Web.UI.HtmlControls.HtmlInputFile fileToUpload;
		protected System.Web.UI.WebControls.Label Header;
		protected System.Web.UI.WebControls.ImageButton GoRoot;
		protected System.Web.UI.WebControls.TextBox setRootTxt;
		protected System.Web.UI.WebControls.Button setRootBtn;
		protected System.Web.UI.WebControls.ImageButton UpBtn;
		protected System.Web.UI.WebControls.PlaceHolder FilesFolders;
		
		private void Page_Load(object sender, System.EventArgs e)
		{			
			// the current directory is stored in Ssession["Path"], if it isn't set, set it to /
			if(Session["Path"] == null || Session["Path"].ToString() == "")
				Session["Path"] = "/";	//default is root directory
			if(Session["Path"].ToString() != "/")			
				Header.Text = "Showing contents of <b>" + Session["Path"].ToString() + "</b> directory.";				
			else
			{
				Header.Text = "Showing contents of <B>root directory.</b>";	
				UpBtn.Visible = false;		// this button has no context in the root dir
				GoRoot.Visible = false;		// same
			}
			showFiles();	// list the files and folders in the current directory
		}

		
		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    						
			this.UpBtn.Command += new System.Web.UI.WebControls.CommandEventHandler(this.ChangePath);
			this.GoRoot.Command += new System.Web.UI.WebControls.CommandEventHandler(this.ChangePath);
			this.UploadBtn.Click += new System.EventHandler(this.UploadBtn_Click);
			this.NewFileBtn.Click += new System.EventHandler(this.NewFileBtn_Click);
			this.NewFolderBtn.Click += new System.EventHandler(this.NewFolderBtn_Click);
			this.setRootBtn.Click += new System.EventHandler(this.setRootBtn_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		
		public void showFiles()
		{					
			// safety checks handled by checkValidSessionPath function
			DirectoryInfo mainDir = checkValidSessionPath();
			if(mainDir == null)	return;	// bail out

			int alternate = 0;	// used for alternating background color in table rows

			foreach(DirectoryInfo d in mainDir.GetDirectories())
			{				
				// build up some literal controls, and buttons for the row of the table representing the directory
				Literal newColumn1 = new Literal();
				newColumn1.Text = "</td> <td>&nbsp;";	
				Literal newColumn2 = new Literal();
				newColumn2.Text = "</td> <td>&nbsp;";	
				Literal newColumn3 = new Literal();
				newColumn3.Text = "</td> <td>";	

				// display a folder icon
				Literal picColumn = new Literal();
				if(alternate%2 == 1)	// alternate back-colour of rows
					picColumn.Text = "<TR><td><img src=pics/folder.gif></td><td>";
				else
					picColumn.Text = "<TR bgcolor='#e8e8e8'><td><img src=pics/folder.gif></td><td>";
				
				// this link changes the path to the directory being clicked
				LinkButton changePathBtn = new LinkButton();
				changePathBtn.Text = d.Name.ToString();
				changePathBtn.CommandArgument = d.Name.ToString();
				changePathBtn.Command += new CommandEventHandler(ChangePath);

				// this link deletes the directory, but it must be empty for the delete to be successful
				HyperLink deleteBtn = new HyperLink();
				deleteBtn.ImageUrl = "pics/delete_icon.gif";
				deleteBtn.NavigateUrl = "javascript:confirmDelete('delete.aspx?Type=Folder&Name=" + Server.UrlEncode(Session["Path"].ToString() + d.Name.ToString()) + "','" + d.Name.ToString()+ "');";	// use client-side confirm function for deleting
				
				Literal endRow = new Literal();
				endRow.Text = "</td></tr>";

				// add the controls to the container in the webform
				this.FilesFolders.Controls.Add(picColumn);
				this.FilesFolders.Controls.Add(changePathBtn);
				this.FilesFolders.Controls.Add(newColumn1);
				this.FilesFolders.Controls.Add(newColumn2);
				this.FilesFolders.Controls.Add(newColumn3);
				this.FilesFolders.Controls.Add(deleteBtn);
				this.FilesFolders.Controls.Add(endRow);

				alternate++;	// bump the int for back-colour alternation
			}

			foreach(FileInfo f in mainDir.GetFiles())
			{	
				// build up some literal controls, and buttons for the row of the table representing the file
				Literal newColumn1 = new Literal();
				newColumn1.Text = "</td> <td>";	
				Literal newColumn2 = new Literal();
				newColumn2.Text = "</td> <td>";	
				Literal newColumn3 = new Literal();
				newColumn3.Text = "</td> <td>";	

				Literal newColumn = new Literal();
				newColumn.Text = "</td> <td>";

				// display a file icon
				Literal picColumn = new Literal();
				if(alternate%2 == 1)
					picColumn.Text = "<TR><td><img src=pics/file.gif></td><td>";
				else
					picColumn.Text = "<TR bgcolor='#e8e8e8'><td><img src=pics/file.gif></td><td>";
				
				// this link goes directly to the file (not edit mode)
				HyperLink goToBtn = new HyperLink();
				goToBtn.Text = f.Name.ToString();
				goToBtn.NavigateUrl = "http://" + Request.ServerVariables["SERVER_NAME"].ToString() + Session["Path"].ToString() + f.Name.ToString();

				Literal gap = new Literal();
				gap.Text = " &nbsp; - &nbsp; ";		

				// this link edits the file when clicked
				HyperLink editBtn = new HyperLink();
				editBtn.Text = "Edit";
				editBtn.ToolTip = f.Name.ToString();
				editBtn.NavigateUrl = "edit.aspx?File=" + Server.UrlEncode(Session["Path"].ToString() + f.Name.ToString());
		
				// work out what string to display for the file, e.g. bytes, kilobytes, or megabytes
				long fileSize = f.Length;
				string fileSizeStr;
				if(fileSize > 1000000) fileSizeStr = fileSize/1000000 + " Mb";
				else if(fileSize > 1000) fileSizeStr = fileSize/1000 + " Kb";
				else fileSizeStr = fileSize + " b";

				// size of file
				Label sizeLbl = new Label();
				sizeLbl.Text = fileSizeStr;

				// last modified datetime of file
				Label modLbl = new Label();
				modLbl.Text = f.LastWriteTime.ToString();
				
				// set up delete button
				HyperLink deleteBtn = new HyperLink();
				deleteBtn.ImageUrl = "pics/delete_icon.gif";
				deleteBtn.NavigateUrl = "javascript:confirmDelete('delete.aspx?Type=File&Name=" + Server.UrlEncode(Session["Path"].ToString() + f.Name.ToString()) + "','" + f.Name.ToString()+ "');";

				Literal endRow = new Literal();
				endRow.Text = "</td></tr>";

				// add controls to container
				this.FilesFolders.Controls.Add(picColumn);
				this.FilesFolders.Controls.Add(goToBtn);
				this.FilesFolders.Controls.Add(gap);
				this.FilesFolders.Controls.Add(editBtn);
				this.FilesFolders.Controls.Add(newColumn1);
				this.FilesFolders.Controls.Add(sizeLbl);
				this.FilesFolders.Controls.Add(newColumn2);
				this.FilesFolders.Controls.Add(modLbl);
				this.FilesFolders.Controls.Add(newColumn3);
				this.FilesFolders.Controls.Add(deleteBtn);
				this.FilesFolders.Controls.Add(endRow);	
				alternate++;
			}
		}

		private void ChangePath(object sender, CommandEventArgs e)
		{			
			if(e.CommandArgument.ToString() == "/")	// goto root
				Session["Path"] = "/";
			else if(e.CommandArgument.ToString() == "../") // go one level up in directory tree
				Session["Path"] = FTP.getParentDirectory();
			else	// add the directory name to the end of the current path
				Session["Path"] = Session["Path"].ToString() + e.CommandArgument.ToString() + "/";			
			Response.Redirect("default.aspx");	// prevent annoying 'repost' of data when page refreshed
		}
		
		private DirectoryInfo checkValidSessionPath(){
			// called by showFiles(), does checks to see if directory to be opened is valid
			DirectoryInfo mainDir;
			try{
				mainDir = new DirectoryInfo(Server.MapPath(Session["Path"].ToString()));
				if(mainDir.Exists == true)
					return mainDir;	// no problems
				else	// directory does not exist
					FTP.ReportError("The directory " + Server.MapPath(Session["Path"].ToString()) + " does not exist.", "Could not find a part of the path \"" + Server.MapPath(Session["Path"].ToString()) + "\".", "If you set the site root manually, try resetting it to the current directory: ./");
			}
			catch(DirectoryNotFoundException DirNotFoundEx){
				FTP.ReportError("The path could not be found", DirNotFoundEx.ToString(), "Try going to <a href='default.aspx'>site root</a>.");
			}
			catch(SecurityException SecEx)
			{
				FTP.ReportError("You do not have permissions to view this directory", SecEx.ToString(), "Set the permissions for ASPNET on this directory (or contact web host)<BR>You may wish to change the root path if you can't get permissions for the root directory.");
			}
			catch(ArgumentException ArgEx)
			{
				FTP.ReportError("The path has invalid characters", ArgEx.ToString(),  "Try renaming the file and removing non-standard characters.");
			}
			catch(Exception Ex){
				FTP.ReportError("Could not get Directory Information", Ex.ToString(),  "Try manually resetting the root path to ./");
			}
			return null;
		}

		private void NewFileBtn_Click(object sender, System.EventArgs e)
		{
			if(this.NewFileText.Text == "")	// user gave no filename
				Response.Write("<script>alert(\"No filename given for new file\\nPlease type in a new filename before clicking 'New File'\");</script>");
			else
			{
				try
				{
					FileInfo file = new FileInfo(Server.MapPath(Session["Path"].ToString() + this.NewFileText.Text.ToString()));
					file.Create();
					Response.Redirect("default.aspx");
				}
				catch(Exception ex)
				{
					FTP.ReportError("Could not create file: " + this.NewFileText.Text.ToString(), ex.ToString(), "Ensure you have write permissions for the current directory");
				}
			}
		}

		private void NewFolderBtn_Click(object sender, System.EventArgs e)
		{
			if(this.NewFolderText.Text == "")	// user gave no folder name
				Response.Write("<script>alert(\"No folder name given for new folder\\nPlease type in a new folder name before clicking 'New Folder'\");</script>");
			else
			{
				try
				{
					DirectoryInfo dir = new DirectoryInfo(Server.MapPath(Session["Path"].ToString() + this.NewFolderText.Text.ToString()));
					dir.Create();
					Response.Redirect("default.aspx");
				}
				catch(Exception ex)
				{
					FTP.ReportError("Could not create folder: " + this.NewFileText.Text.ToString(), ex.ToString(), "Ensure you have write permissions for the current directory");
				}
			}
		}

		private void UploadBtn_Click(object sender, System.EventArgs e)
		{
			if(fileToUpload.PostedFile.FileName == "")	// no file selected
				Response.Write("<script>alert(\"No file selected for upload\\nPlease click browse and select the file you wish to upload\");</script>");
			else
			{
				try
				{
					string filename = fileToUpload.PostedFile.FileName;						
					string togo = Session["Path"].ToString() + filename.Remove(0, filename.LastIndexOf("\\") + 1);
					fileToUpload.PostedFile.SaveAs(Server.MapPath(togo));	 

					// get size of file with appropriate expression of size
					long fileSize = fileToUpload.PostedFile.ContentLength;
					string fileSizeStr;
					if(fileSize > 1000000) fileSizeStr = fileSize/1000000 + " Mb";
					else if(fileSize > 1000) fileSizeStr = fileSize/1000 + " Kb";
					else fileSizeStr = fileSize + " b";
					
					// notify user of success
					Response.Write("<script>alert(\"Upload Successful...\\nName: " + filename.Remove(0, filename.LastIndexOf("\\") + 1) + "\\nSize: " + fileSizeStr + "\"); document.location=\"default.aspx\";</script>");				
				}
				catch(Exception ex)
				{
					FTP.ReportError("Upload failed.", ex.ToString(), "The file may be too large");
				}
			}
		}

		private void setRootBtn_Click(object sender, System.EventArgs e)
		{
			// this function can be used when users don't have permissions for the root directory of a web server, 
			// they can upload this script to their own directory, and enter ./ as the root.
			if(this.setRootTxt.Text == "")	// user gave no root path 
				Response.Write("<script>alert(\"No path given to change the site root to.\\nPlease enter a path such as mySubDir\"); document.location=\"default.aspx\";</script>");				
			else
			{
				string rootText = this.setRootTxt.Text;				
				// add a trailing / to path if there isn't one already
				if(rootText.LastIndexOf("/") != rootText.Length - 1) 
					rootText += "/";
				Session["Path"] = rootText;
				Response.Redirect("default.aspx");
			}
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -