using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; namespace FineUIPro.Web { public partial class source_file : PageBase { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string file = Request.QueryString["file"].ToLower(); if (file.StartsWith("http://") || file.StartsWith("https://")) { desc.Text = String.Format("

在新窗口打开", file); return; } // 不是网站根目录下的文件 if (!UnderRootPath(file)) { return; } // 不允许下载文件的目录 string basePath = GetBasePath(file); List disallowPaths = new List { "bin", "obj", "upload", "Properties" }; if (disallowPaths.Contains(basePath)) { return; } // 只能下载指定类型文件 string fileType = GetFileType(file); List allowFileTypes = new List { "aspx", "ascx", "master", "ashx", "cs", "xml", "css", "js" }; if (!allowFileTypes.Contains(fileType)) { return; } // 读取文件内容 string content = File.ReadAllText(Server.MapPath(file)); desc.Text = "
" + HttpUtility.HtmlEncode(content) + "
"; // linenums } } private bool UnderRootPath(string fileName) { string filePath = Server.MapPath(fileName); string rootPath = Server.MapPath("~/"); return filePath.StartsWith(rootPath); } private string GetBasePath(string fileName) { string filePath = Server.MapPath(fileName); string rootPath = Server.MapPath("~/"); string basePath = filePath.Substring(rootPath.Length); int slashIndex = basePath.IndexOf("\\"); if (slashIndex >= 0) { basePath = basePath.Substring(0, slashIndex); } return basePath; } private string GetFileType(string fileName) { string fileType = String.Empty; int lastDotIndex = fileName.ToLower().LastIndexOf("."); if (lastDotIndex >= 0) { fileType = fileName.Substring(lastDotIndex + 1); } return fileType; } } }