using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Mammonth.Common {

    /// <summary>
    /// 自定义文件助手类
    /// </summary>
    /// <remarks>
    /// 创建：ZhaoShunLu 2013-3-4 
    /// </remarks>
    public class FileHelper {

        /// <summary>
        /// FileHelper 构造函数
        /// </summary>
        public FileHelper() {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }
        /// <summary>
        /// 处理上传图片信息,如：删除旧的无效图片，上传新的图片
        /// <para>特别为swfupload上传组件准备</para>
        /// </summary>
        /// <param name="context">System.Web.HttpContext</param>
        /// <param name="IsNew">是否新建记录</param>      
        /// <param name="targetfolder">目标文件夹,是相对路径,如：oa\data\00001\hotel\240,不能以\开头结尾</param>     
        /// <param name="source">新文件名称,不含路径</param>
        /// <param name="original">原始文件名称,不含路径（如果是新记录IsNew = true，那么此参数没有作用，可以为null）</param>
        /// <returns></returns>
        /// <remarks>
        /// 创建：ZhaoShunLu 2014-06-24 
        /// </remarks>
        public static bool AccessUpFile(System.Web.HttpContext context, bool IsNew, string targetfolder, string source, string original) {

            if (targetfolder.StartsWith("\\")) targetfolder = targetfolder.Remove(0, 1);
            if (targetfolder.EndsWith("\\")) targetfolder = targetfolder.Remove(targetfolder.Length - 1, 1);

            string rootfolder = context.Server.MapPath("/");//网站物理根目录,后面已经有\，如c:\wwwroot\web\

            return AccessUpFile(IsNew, rootfolder, targetfolder, source, original);
        }

        /// <summary>
        /// 处理上传图片信息,如：删除旧的无效图片，上传新的图片
        /// <para>特别为swfupload上传组件准备</para>
        /// </summary>
        /// <param name="IsNew">是否新建记录</param>
        /// <param name="rootfolder">网站根目录必须以\结尾,是物理路径</param>
        /// <param name="targetfolder">目标文件夹,是相对路径,结尾没有\</param>     
        /// <param name="source">新文件名称,不含路径</param>
        /// <param name="original">原始文件名称,不含路径（如果是新记录IsNew = true，那么此参数没有作用，可以为null）</param>
        /// <returns></returns>
        /// <remarks>
        /// 创建：ZhaoShunLu 2013-3-4 
        /// </remarks>
        public static bool AccessUpFile(bool IsNew, string rootfolder, string targetfolder, string source, string original) {
            //临时文件夹的路径
            //rootfolder + "uploads\\swfupload"
            //是固定不变的。

            //如果目标文件夹不存在就要先创建
            if (!System.IO.Directory.Exists(rootfolder + targetfolder)) {
                if (targetfolder.IndexOf("\\") > 0) {
                    string[] fs = targetfolder.Split(new char[] { '\\' });
                    string _path = rootfolder;
                    for (int i = 0; i < fs.Length; i++) {
                        if (i == 0)
                            _path += fs[i];
                        else
                            _path += "\\" + fs[i];

                        if (!System.IO.Directory.Exists(_path)) {
                            System.IO.Directory.CreateDirectory(_path);
                        }
                    }
                } else {
                    System.IO.Directory.CreateDirectory(rootfolder + targetfolder);
                }
            }

            if (IsNew) {//新建记录 
                if (source != "") {
                    //移动临时文件 到 目标文件夹
                    return FileHelper.MoveFile(
                        rootfolder + "uploads\\swfupload\\" + source,//临时文件
                        rootfolder + targetfolder + "\\" + source);
                }
                return true;

            } else {
                //修改记录，如果新文件和原来的文件名称不一样，就要更新文件
                if (source != original)//是否需要替换文件
                {
                    //如果目标文件夹不存在就要先创建
                    if (!System.IO.Directory.Exists(rootfolder + targetfolder)) {
                        if (targetfolder.IndexOf("\\") > 0) {
                            string[] fs = targetfolder.Split(new char[] { '\\' });
                            string _path = rootfolder;
                            for (int i = 0; i < fs.Length; i++) {
                                if (i == 0)
                                    _path += fs[i];
                                else
                                    _path += "\\" + fs[i];

                                if (!System.IO.Directory.Exists(_path)) {
                                    System.IO.Directory.CreateDirectory(_path);
                                }
                            }
                        } else {
                            System.IO.Directory.CreateDirectory(rootfolder + targetfolder);
                        }
                    }

                    //替换文件
                    return FileHelper.ReplaceFile(
                          rootfolder + targetfolder + "\\" + original,//原来的文件
                          rootfolder + "uploads\\swfupload\\" + source,//临时文件
                          rootfolder + targetfolder + "\\" + source);
                }
            }
            return true;//默认返回真
        }

        /// <summary>
        /// 移动文件
        /// 将来源文件移动到目标文件        
        /// </summary>
        /// <param name="source">来源文件</param>
        /// <param name="target">目标文件</param>
        /// <param name="overwrite">是否允许覆盖同名文件 默认false</param>
        /// <returns></returns>
        /// <remarks>
        /// 创建：ZhaoShunLu 2013-3-4 
        /// </remarks>
        public static bool MoveFile(string source, string target, bool overwrite = false) {
            //从临时文件夹中复制文件
            if (source != "" && System.IO.File.Exists(source)) {
                try {
                    string spath = System.IO.Path.GetDirectoryName(target);
                    if (!System.IO.Directory.Exists(spath))
                        System.IO.Directory.CreateDirectory(spath);
                    //如果目标文件已经存在并且是只读属性，就要更改正常属性，否则替换会异常失败
                    if (File.Exists(target)) {
                        FileInfo finfo = new FileInfo(target);
                        finfo = new FileInfo(target);
                        if (finfo.IsReadOnly) File.SetAttributes(target, FileAttributes.Normal);
                    }
                    System.IO.File.Copy(source, target, overwrite);//复制到酒店文件夹
                    System.IO.File.Delete(source);//删除临时文件
                    return true;
                } catch// (System.Exception ex)
                {
                    return false;
                }

            } else {
                return false;
            }
        }

        /// <summary>
        /// 替换文件
        /// 删掉原始文件，将来源文件移动到目标文件      
        /// </summary>
        /// <param name="original">原始文件</param>
        /// <param name="source">来源文件</param>
        /// <param name="target">目标文件</param>
        /// <returns></returns>
        /// <remarks>
        /// 创建：ZhaoShunLu 2013-3-4 
        /// </remarks>
        public static bool ReplaceFile(string original, string source, string target) {
            //如果原始文件存在就删除原来的图片  
            if (System.IO.File.Exists(original))
                System.IO.File.Delete(original);
            //移动文件
            return FileHelper.MoveFile(source, target);
        }

        /// <summary>
        /// 删掉文件
        /// </summary>
        /// <param name="source">来源文件</param>
        /// <returns></returns>
        /// <remarks>
        /// 创建：ZhaoShunLu 2013-3-4 
        /// </remarks>
        public static bool DeleteFile(string source) {
            //如果原始文件存在就删除原来的图片  
            try {
                if (System.IO.File.Exists(source))
                    System.IO.File.Delete(source);
                return true;
            } catch (System.Exception ex) {
                return false;
            }
        }

        /// <summary>
        /// 读取文件内容
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        /// <remarks>
        /// 创建：ZhaoShunLu 2013-3-4 
        /// </remarks>
        public static string Read(string path) {
            StreamReader sr = new StreamReader(path, System.Text.Encoding.Default);
            string text = sr.ReadToEnd();
            sr.Close();
            return text;
        }

        /// <summary>
        /// 写入文件内容
        /// </summary>
        /// <param name="path"></param>
        /// <param name="text"></param>
        /// <remarks>
        /// 创建：ZhaoShunLu 2013-3-4 
        /// </remarks>
        public static void Write(string path, string text, System.Text.Encoding encode = null) {
            if (encode == null)
                encode = System.Text.Encoding.Default;
            //如果目标文件已经存在并且是只读属性，就要更改正常属性，否则替换会异常失败
            if (File.Exists(path)) {
                FileInfo finfo = new FileInfo(path);
                finfo = new FileInfo(path);
                if (finfo.IsReadOnly) File.SetAttributes(path, FileAttributes.Normal);
            }
            StreamWriter sr = new StreamWriter(path, false, encode);
            sr.Write(text);
            sr.Close();
        }

        /// <summary>
        /// 复制文件夹
        /// </summary>
        /// <param name="from">来源文件夹，不以\结尾</param>
        /// <param name="to">目标文件夹，不以\结尾</param>
        /// <remarks>
        /// 创建：ZhaoShunLu 2014-8-25 
        /// </remarks> 
        public static void CopyFolder(string from, string to) {
            if (!Directory.Exists(to))
                Directory.CreateDirectory(to);
            if (to.EndsWith("\\")) {
                to = to.Substring(0, to.Length - 1);
            }
            // 子文件夹
            foreach (string sub in Directory.GetDirectories(from))
                CopyFolder(sub + "\\", to + "\\" + Path.GetFileName(sub));

            // 文件
            foreach (string file in Directory.GetFiles(from))
                File.Copy(file, to + "\\" + Path.GetFileName(file), true);
        }
    }
}
