C# Web对文件的管理
/// <summary> /// 创建新文件 /// </summary> /// <param name="parentPath">文件路径</param> /// <param name="FileName">文件名称</param> public void AddFile(string parentPath, string FileName) { parentPath = Server.MapPath(parentPath); bool flag = !Directory.Exists(parentPath + FileName); if (!flag) { HttpContext.Current.Response.Write("<script>alert('该文件以存在');history.go(-1);</script>\uFFFD"); HttpContext.Current.Response.End(); } else { Directory.CreateDirectory(parentPath + FileName); } } /// <summary> /// 删除文件 /// </summary> /// <param name="fileName">文件路径</param> /// <param name="fileType">文件类型</param> public void Delete(string fileurl, string fileType) { bool flag = fileType != "file";//判断文件的类型 file为文件 folder 为文件夹 if (!flag) {//删除文件 flag = File.Exists(fileurl); if (flag) { File.Delete(fileurl); } } else {//删除文件夹 flag = Directory.Exists(fileurl); if (flag) { DirectoryInfo directoryInfo = new DirectoryInfo(fileurl); flag = (directoryInfo.GetDirectories().Length <= 0) && (directoryInfo.GetFiles().Length <= 0); if (!flag) { HttpContext.Current.Response.Write("<script>alert('请先删除文件的子文件');history.go(-1);</script>"); HttpContext.Current.Response.End(); } else { Directory.Delete(fileurl); } } } } /// <summary> /// 获得指定文件的文件内容 /// </summary> /// <param name="parentPath">相对路径</param> /// <returns></returns> public DataSet GetFileList(string parentPath) { DataRow row; string filePath = parentPath; DataSet set = new DataSet(); DataTable table = new DataTable(); table.Columns.Add("FileType");//指定文件类型 folder 为文件夹 table.Columns.Add("FileName");//文件名称 table.Columns.Add("FileIcon");//文件的图标 table.Columns.Add("FileUrl");//文件的相对路径+文件名称 table.Columns.Add("FilePath");//文件的相对路径 table.Columns.Add("FileSize");//文件大小 table.Columns.Add("FileUrlType");//文件的相对路径+文件名称+类型 DirectoryInfo info = new DirectoryInfo(HttpContext.Current.Server.MapPath(filePath)); foreach (DirectoryInfo info2 in info.GetDirectories()) {//调取文件夹 row = table.NewRow(); row["FileType"] = "folder"; row["FileName"] = info2.Name; row["FileIcon"] = "<img src=\"Images/closedfolder.gif\" border=\"0\" />"; row["FileUrl"] = filePath + "/" + info2.Name; row["FilePath"] = filePath; row["FileSize"] = ""; row["FileUrlType"] = filePath + "/" + info2.Name + ";" + "folder"; table.Rows.Add(row); } foreach (FileInfo info3 in info.GetFiles()) {//调取文件 row = table.NewRow(); row["FileType"] = "file"; row["FileName"] = info3.Name; row["FileIcon"] = "<img src=\"Images/FileIcon/.gif\" class=\"itemimg\" />";//根据扩展名获得Icon row["FileUrl"] = filePath + "/" + info3.Name; row["FilePath"] = filePath; row["FileSize"] = (info3.Length / 0x3e8L) + "K"; row["FileUrlType"] = filePath + "/" + info3.Name + ";" + "file"; table.Rows.Add(row); } set.Tables.Add(table); return set; }