文件夹操作

本文介绍了一个用于处理文件上传、目录创建以及HTML页面生成的实用类。涉及如何根据不同的类型创建目录、验证文件上传的有效性、复制文件夹、以及根据模板生成HTML文件等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.IO;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Globalization;


/// <summary>
///DirectorysandFiles 的摘要说明
/// </summary>
public class DirectorysandFiles
{
    List<string> HtmlData = new List<string>();
public DirectorysandFiles()
{
//
//TODO: 在此处添加构造函数逻辑
//
}


    /// <summary>
    /// 如果创建成功将返回创建的子文件夹的物理路径,如果创建不成功将返回空字符串
    /// </summary>
    /// <param name="dirType">
    /// 根据dirType创建不同的子文件夹
    /// dirType值为栏目类型(MenuType)、专题类型(TopicType)、上传类型(UploadType)
    /// </param>
    /// <param name="fileType">
    /// 如果栏目类型为MenuType,根据fileType的值在指定子文件夹下创建子文件夹
    /// fileType的值为Image、Flash、File
    /// 如果栏目类型为TemplateType,fileType的值为空字符串
    /// </param>
    /// <returns></returns>
    public string CreateDirectory(string dirType, string fileType)
    {        
        StringBuilder dir = new StringBuilder(HttpContext.Current.Request.PhysicalApplicationPath);
        string filedirectory =""; 
        string filepath = "";
        switch(dirType)
        {
            case "UploadType":
                filedirectory = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);                
                filepath = "UpFiles\\" + fileType + "\\" + filedirectory; break;


            case "MenuType":
                Menu menu = new Menu();
                //创建本地栏目对应的文件夹,文件夹由“Cata”+随机1位数 + ID + 随机1位数组成
                filepath = "Catalog" + (new Random().Next(10)) + menu.GetNextMenuID()+(new Random().Next(10));break;


            case "TopicType":                 
                //创建专题对应的文件夹,文件夹由“Cata”+随机1位数 + ID + 随机1位数组成
                Topic topic = new Topic();
                filepath = "Catalog" + (new Random().Next(10)) + topic.GetNextTopicID() + (new Random().Next(10));
                filepath = "Topic\\" + filepath; break;
        }
        string fullUploadPath = Path.Combine(dir.ToString(), filepath);
        if (!Directory.Exists(fullUploadPath))
        {
            try
            {
                Directory.CreateDirectory(fullUploadPath);
                MsgInfo.showMessage("DirectorysandFiles", 9);
            }
            catch
            {
                MsgInfo.showMessage("DirectorysandFiles", 1);                
                fullUploadPath = "";                
            }
        }
        return fullUploadPath; 
    }


    /// <summary>
    /// 是否支持该文件的上传,支持返回为true,不支持返回为false
    /// </summary>
    /// <param name="fileType">fileType的值为Image、Flash、File</param>
    /// <returns></returns>
    public bool IsSupportUpload(FileUpload fuControl, string fileType)
    {
        bool isSupport = true;
        string fileunit = ConfigurationManager.AppSettings.Get("UNIT");
        int filesize = Convert.ToInt16(ConfigurationManager.AppSettings.Get(fileType));
        if (fileunit == "M" || fileunit == "m")
        {
            filesize = filesize * 1024 * 1024;
        }
        else if (fileunit == "K" || fileunit == "k")
        {
            filesize = filesize * 1024;
        }
        if (fuControl.PostedFile.FileName == "")
        {
            isSupport = false;
            return isSupport;
        }
        if (fuControl.PostedFile.ContentLength > filesize)
        {
            isSupport = false;
            return isSupport;
        }
        
        string[][] AllowedExtensions = new string[][] { 
            new string[]{"jpeg", "jpg", "png","gif","bmp"},
            new string[]{"fla", "flv","swf"},
            new string[]{"css","7z", "aiff", "asf", "avi", "csv", "doc", "docx","gz","gzip", "mid", "mov", "mp3", "mp4", "mpc", "mpeg", "mpg", "ods", "odt", "pdf", "ppt", "pptx", "pxd", "qt", "ram", "rar", "rm", "rmi", "rmvb", "rtf", "sdc", "sitd", "sxc", "sxw", "tar", "tgz", "tif", "tiff", "txt", "vsd", "wav", "wma", "wmv", "xls", "xlsx", "zip" }};
        //判断文件类型
        string extension = Path.GetExtension(fuControl.PostedFile.FileName).ToLower();
        int filevalid = 0;
        int index = 0;
        switch (fileType)
        {
            case "Image": break;
            case "Flash": index = 1; break;
            case "File": index = 2; break;
        }
        for (int i = 0; i < AllowedExtensions[index].Length; i++)
        {
            if (String.Concat("." + AllowedExtensions[index][i]) == extension)
            {
                filevalid = 1;
                break;
            }
        }
        if (filevalid == 0)
        {
            isSupport = false;
        }
        return isSupport;
    }


    /// <summary>
    /// 根据dirType、fuControl、fileType上传不同的子文件
    /// </summary>
    /// <param name="dirType">
    /// 根据dirType上传不同的子文件
    /// dirType值为栏目类型(MenuType)、模板类型(TopicType)、上传类型(UploadType)
    /// </param>
    /// <param name="fuControl">上传控件</param>
    /// <param name="fileType">文件类型</param>
    /// <returns>
    /// 如果dirType值为UploadType,保存成功返回文件的相对路径,格式为“/UpFiles/fileType/199001/*.*”;
    /// 如果dirType值为TopicType,保存成功返回文件的相对路径,格式为“/Topic/专题子文件夹/images/*.*”
    /// 如果保存失败返回空字符串</returns>
    public string CreateFile(string dirType, FileUpload fuControl, string fileType, string catalogName)
    {
        string physicalPath = "";
        string virtualPath = "";
        if(!IsSupportUpload(fuControl,fileType))
        {
            MsgInfo.showMessage("DirectorysandFiles", 0);            
            return virtualPath;
        }
        switch (dirType)
        {
            case "UploadType": 
                physicalPath = CreateDirectory("UploadType", fileType);
                if(physicalPath == "") return virtualPath;
                break;
            case "TopicType":
                physicalPath = GetPhysicalPath("TopicType",catalogName) + "\\images";
                break;
        }       
        string extension = Path.GetExtension(fuControl.PostedFile.FileName);
        Random r = new Random();
        int randnum = (int)r.NextDouble() * 10000;
        string filename = DateTime.Now.ToString("yyyyMMddhhmmss") + (new Random().Next(1000, 10000)) + extension;         
        physicalPath = Path.Combine(physicalPath, filename);
        try
        {                
            fuControl.PostedFile.SaveAs(physicalPath); //上传文件
            virtualPath = GetVirtualPath(dirType, physicalPath);
        }
        catch
        {
            MsgInfo.showMessage("DirectorysandFiles", 2);
            virtualPath = "";
        }
        return virtualPath;
    }


    /// <summary>
    /// 根据文件的物理路径和文件的类型返回虚拟路径
    /// </summary>
    /// <param name="physicalPath">物理路径</param>
    /// <param name="fileType">fileType的值为Image、Flash、File</param>
    /// <returns></returns>
    public string GetVirtualPath(string dirType,string physicalPath)
    {
        string virtualPath = "";
        int index = 0;
        switch (dirType)
        {
            case "UploadType":
                index = physicalPath.IndexOf("UpFiles");
                break;
            case "TopicType":
                index = physicalPath.IndexOf("Topic");
                break;
        }
        virtualPath = physicalPath.Substring(index);
        virtualPath = virtualPath.Replace('\\', '/');
        virtualPath = "/" + virtualPath;
        return virtualPath;
    }


    /// <summary>
    /// 根据typeName和文件夹的名称返回其物理路径
    /// </summary>
    /// <param name="typeName">
    /// 根据typeName创建不同的HTML文件
    /// typeName值为栏目类型(MenuType)、专题类型(TopicType)
    /// </param>
    /// <param name="dirName">文件夹名称</param>
    /// <returns></returns>
    public string GetPhysicalPath(string typeName,string dirName)
    {
        string physicalPath = "";
        switch (typeName)
        {
            case "MenuType":
                physicalPath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, dirName);
                break;
            case "TopicType": 
                physicalPath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "Topic\\" + dirName);
                break;
            case "html":
                physicalPath = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, dirName);
                break;
        }       
        return physicalPath;
    }


    /// <summary>
    /// 根据物理路径获取创建的文件夹的名称
    /// </summary>
    /// <param name="physicalPath">物理路径</param>
    /// <returns></returns>
    public string GetDirectoryName(string physicalPath)
    {        
        int index = physicalPath.LastIndexOf('\\');
        if (index == physicalPath.Length - 1) physicalPath = physicalPath.Substring(0,index);
        return physicalPath.Substring(index + 1);       
    }


    /// <summary>
    /// 复制原文件夹下的所有文件及子文件夹到目标文件夹
    /// </summary>
    /// <param name="SourceDir">原文件夹</param>
    /// <param name="TargetDir">目标文件夹</param>
    /// <returns>如果复制成功返回值为1,否则为-1</returns>
    public int CopyAll(string SourceDir, string TargetDir)
    {
        int result = -1;
        try
        {
            CopyFiles(SourceDir, TargetDir);            
            result = 1;
        }
        catch
        {
            MsgInfo.showMessage("DirectorysandFiles", 10);            
        }
        return result;
    }


    public void CopyFiles(string SourceDir, string TargetDir)
    {
        DirectoryInfo source = new DirectoryInfo(SourceDir);
        DirectoryInfo target = new DirectoryInfo(TargetDir);


        if (!target.Exists) target.Create();
        FileInfo[] sourceFiles = source.GetFiles();
        int filescount = sourceFiles.Length;
        for (int i = 0; i < filescount; ++i)
        {
            //复制所有文件
            File.Copy(sourceFiles[i].FullName, target.FullName + "\\" + sourceFiles[i].Name, true);
        }
        //得到源文件夹下所有的文件夹
        DirectoryInfo[] sourceDirectories = source.GetDirectories();
        for (int j = 0; j < sourceDirectories.Length; ++j)
        {
            //递归复制所有文件夹
            CopyFiles(sourceDirectories[j].FullName, target.FullName + "\\" + sourceDirectories[j].Name);
        }
    }


    /// <summary>
    /// 根据htmlType的值,确定创建HTML文件
    /// </summary>
    /// <param name="typeName">
    /// 根据typeName创建不同的HTML文件
    /// typeName值为栏目类型(MenuType)、专题类型(TopicType)
    /// </param>
    /// <param name="typeID">
    /// 该类型下的ID值
    /// 如果为MenuType,则typeID为MenuID值,如果为TopicType,则为TopicID值
    /// </param>
    /// <returns></returns>
    public string CreateHTML(string typeName, int typeID, string fileName)
    {
        StringBuilder htmltext = new StringBuilder();
        string fullpath = "";
        string catalogName = "";
        try
        {
            //获取该栏目下的模板文件HTMLPage.htm
            switch (typeName)
            {
                case "MenuType":
                    Menu menu = new Menu();
                    catalogName = menu.GetMenuChar(typeID);
                    break;
                case "TopicType":
                    Topic topic = new Topic();
                    catalogName = topic.GetTopicCatalogbyTopicID(typeID);
                    break;
                case "html":
                    //文章发布
                    //fullpath = HttpContext.Current.Server.MapPath("~/html/" + fileName);
                    break;
            }
            fullpath = Path.Combine(GetPhysicalPath(typeName, catalogName), "HTMLPage.htm");  //模板路径
            using (StreamReader sr = new StreamReader(fullpath))   //读取HTML模板
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    htmltext.Append(line);
                }
                sr.Close();
            }


            //获取当前文章需要填充到HTML的字段内容
            for (int i = 0; i < HtmlData.Count; i++)
            {
                htmltext.Replace("$htmlformat[" + i + "]", HtmlData[i]);
            }


            //----------生成htm文件------------------――
            //fullpath = Path.Combine(GetPhysicalPath(typeName, catalogName), fileName);
            if (typeName=="html")
            {
                fullpath = HttpContext.Current.Server.MapPath("~/html/" + fileName);//写入路径
            }
            using (StreamWriter sw = new StreamWriter(fullpath,false))
            {
                sw.WriteLine(htmltext);
                sw.Flush();
                sw.Close();
            }
        }
        catch
        {


            MsgInfo.showMessage("DirectorysandFiles", 4);
            fileName = "";
        }
        return fileName;
    }


    public void AddHtmlData(string dataString)
    {
        HtmlData.Add(dataString);
    }


    /// <summary>
    /// 判断是否上传了导图
    /// </summary>
    /// <param name="picPath"></param>
    /// <returns>如果没有返回空字符串,如果有返回导图路径</returns>
    public string smallPicPath(string picPath)
    {
        int index = picPath.LastIndexOf('/');
        if (picPath.Substring(index + 1) == "noPic.png") return "";
        else return picPath;
    }


    public string GetFileName()
    {
        Random ra = new Random(unchecked((int)DateTime.Now.Ticks));
        string filename = DateTime.Now.ToString("yyyyMMddhhmmss") + (ra.Next(1000, 10000)) + ".htm";
        return filename;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值