using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Web;

using System.Net;

using System.Threading;

using EcmaScript.NET;

using Yahoo.Yui.Compressor;

using System.Xml;

using System.Data.OleDb;

using System.Data;

using System.Collections;

using System.Web.UI.HtmlControls;

using System.Drawing.Imaging;




namespace Common

{

    public class fileHelper

    {

        #region 下载文件

        /// <summary>

        ///功能说明:文件下载类--不管是什么格式的文件,都能够弹出打开/保存窗口,

        ///包括使用下载工具下载

        ///继承于IHttpHandler接口,可以用来自定义HTTP 处理程序同步处理HTTP的请求

        /// </summary>

        /// <param name="context"></param>

        public static void Proce***equest(HttpContext context)

        {

            HttpResponse Response = context.Response;

            HttpRequest Request = context.Request;


            System.IO.Stream iStream = null;


            byte[] buffer = new Byte[10240];


            int length;


            long dataToRead;


            try

            {

                string filename = Request["fn"];


                string filepath = HttpContext.Current.Server.MapPath("~/") + filename; //待下载的文件路径


                iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,

                    System.IO.FileAccess.Read, System.IO.FileShare.Read);

                Response.Clear();


                dataToRead = iStream.Length;


                long p = 0;

                if (Request.Headers["Range"] != null)

                {

                    Response.StatusCode = 206;

                    p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));

                }

                if (p != 0)

                {

                    Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString());

                }

                Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString());

                Response.ContentType = "application/octet-stream";

                Response.AddHeader("Content-Disposition", "p_w_upload; filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(Path.GetFileName(filename))));


                iStream.Position = p;

                dataToRead = dataToRead - p;


                while (dataToRead > 0)

                {

                    if (Response.IsClientConnected)

                    {

                        length = iStream.Read(buffer, 0, 10240);


                        Response.OutputStream.Write(buffer, 0, length);

                        Response.Flush();


                        buffer = new Byte[10240];

                        dataToRead = dataToRead - length;

                    }

                    else

                    {

                        dataToRead = -1;

                    }

                }

            }

            catch (Exception ex)

            {

                Response.Write("Error : " + ex.Message);

            }

            finally

            {

                if (iStream != null)

                {

                    iStream.Close();

                }

                Response.End();

            }

        }


        /// <summary>

        /// 下载方法二

        /// </summary>

        /// <param name="_Request"></param>

        /// <param name="_Response"></param>

        /// <param name="_fileName"></param>

        /// <param name="_fullPath"></param>

        /// <param name="_speed"></param>

        /// <returns></returns>

        public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)

        {

            try

            {

                FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                BinaryReader br = new BinaryReader(myFile);

                try

                {

                    _Response.AddHeader("Accept-Ranges", "bytes");

                    _Response.Buffer = false;

                    long fileLength = myFile.Length;

                    long startBytes = 0;


                    double pack = 10240; //10K bytes

                    //int sleep = 200;   //每秒5次   即5*10K bytes每秒

                    int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;

                    if (_Request.Headers["Range"] != null)

                    {

                        _Response.StatusCode = 206;

                        string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });

                        startBytes = Convert.ToInt64(range[1]);

                    }

                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());

                    if (startBytes != 0)

                    {

                        //Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));

                    }

                    _Response.AddHeader("Connection", "Keep-Alive");

                    _Response.ContentType = "application/octet-stream";

                    _Response.AddHeader("Content-Disposition", "p_w_upload;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));


                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);

                    int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;


                    for (int i = 0; i < maxCount; i++)

                    {

                        if (_Response.IsClientConnected)

                        {

                            _Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));

                            Thread.Sleep(sleep);

                        }

                        else

                        {

                            i = maxCount;

                        }

                    }

                }

                catch

                {

                    return false;

                }

                finally

                {

                    br.Close();


                    myFile.Close();

                }

            }

            catch

            {

                return false;

            }

            return true;

        }


        /// <summary>

        /// 从图片地址下载图片到本地磁盘

        /// </summary>

        /// <param name="ToLocalPath">图片本地磁盘地址</param>

        /// <param name="Url">图片网址</param>

        /// <returns></returns>

        public static bool SavePhotoFromUrl(string FileName, string Url)

        {

            bool Value = false;

            WebResponse response = null;

            Stream stream = null;


            try

            {

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);


                response = request.GetResponse();

                stream = response.GetResponseStream();


                if (!response.ContentType.ToLower().StartsWith("text/"))

                {

                    Value = SaveBinaryFile(response, FileName);

                }

            }

            catch (Exception err)

            {

                //Common.PageValidate.WriteFile("下载错误:" + err.Message.ToString());

            }

            return Value;

        }

        /// <summary>

        /// Save a binary file to disk.

        /// </summary>

        /// <param name="response">The response used to save the file</param>

        // 将二进制文件保存到磁盘

        private static bool SaveBinaryFile(WebResponse response, string FileName)

        {

            bool Value = true;

            byte[] buffer = new byte[1024];

            try

            {

                if (File.Exists(FileName))

                {

                    File.Delete(FileName);

                }

                Stream outStream = System.IO.File.Create(FileName);

                Stream inStream = response.GetResponseStream();


                int l;

                do

                {

                    l = inStream.Read(buffer, 0, buffer.Length);

                    if (l > 0)

                        outStream.Write(buffer, 0, l);

                }

                while (l > 0);


                outStream.Close();

                inStream.Close();

            }

            catch (Exception ex)

            {

                Value = false;

            }

            return Value;

        }


        #endregion


        #region 抓取网页数据

        /// <summary>

        /// 获取网页数据

        /// </summary>

        /// <param name="PageURL"></param>

        /// <returns></returns>

        public static string GetPageCode(string PageURL)

        {

            string Charset = "gb2312";

            try

            {

                //存放目标网页的html

                String strHtml = "";

                //连接到目标网页

                HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(PageURL);

                wreq.Headers.Add("X_FORWARDED_FOR", "101.0.0.11"); //发送X_FORWARDED_FOR头(若是用取源IP的方式,可以用这个来造假IP,对日志的记录无效)  


                wreq.Method = "Get";

                wreq.KeepAlive = true;

                wreq.ContentType = "application/x-www-form-urlencoded";

                wreq.AllowAutoRedirect = true;

                wreq.Accept = "p_w_picpath/gif, p_w_picpath/x-xbitmap, p_w_picpath/jpeg, p_w_picpath/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";

                wreq.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)";


                CookieContainer cookieCon = new CookieContainer();

                wreq.CookieContainer = cookieCon;


                HttpWebResponse wresp = null;

                try

                {

                    wresp = (HttpWebResponse)wreq.GetResponse();

                }

                catch (WebException ex)

                {

                    wresp = (HttpWebResponse)ex.Response;

                }


                //采用流读取,并确定编码方式

                Stream s = wresp.GetResponseStream();

                StreamReader objReader = new StreamReader(s, System.Text.Encoding.GetEncoding(Charset));


                string strLine = "";

                //读取

                while (strLine != null)

                {

                    strLine = objReader.ReadLine();

                    if (strLine != null)

                    {

                        strHtml += strLine + "\r\n";

                    }

                }

                return strHtml;

            }

            catch (Exception n) //遇到错误,打印错误

            {

                return n.Message;

            }

        }

        #endregion


        #region 压缩合并cssjs文件

        /// <summary>

        /// 压缩合并css文件

        /// </summary>

        /// <param name="filePath"></param>

        /// <param name="cssContent"></param>

        /// <returns></returns>

        public static bool CompressCssFile(string filePath, ref string cssContent)

        {

            bool ret = true;

            try

            {

                //目录不存在

                string[] pathList = filePath.Split(',');

                //获取该文件夹下所有js或者css文件

                HttpContext ctx = HttpContext.Current;

                string newDir = ctx.Server.MapPath("../style/");

                string filetype = ".min.css";

                string newFileName = GetNewFileName(filePath);

                string newFilePath = newDir + newFileName + filetype;

                if (File.Exists(newFilePath))

                {

                    FileInfo Nowinfo = new FileInfo(newFilePath);

                    cssContent = File.ReadAllText(Nowinfo.FullName, Encoding.UTF8);

                    return true;

                }

                foreach (string path in pathList)

                {

                    if (ctx.Server.MapPath(path) != "")

                    {

                        FileInfo info = new FileInfo(ctx.Server.MapPath(path));

                        string strContent = File.ReadAllText(info.FullName, Encoding.UTF8);

                        if (info.Extension.ToLower() == ".css")

                        {

                            if (!info.FullName.ToLower().EndsWith(".no.css"))

                            {

                                if (!info.FullName.ToLower().EndsWith(".min.css"))

                                {

                                    strContent = CssCompressor.Compress(strContent);

                                }

                                cssContent += strContent;

                            }

                        }

                    }

                }

                var newFile = new FileInfo(newFilePath);

                File.WriteAllText(newFile.FullName, cssContent, Encoding.UTF8);

            }

            catch (Exception ex)

            { ret = false; }

            return ret;

        }


        /// <summary>

        /// 压缩合并js文件

        /// </summary>

        /// <param name="filePath"></param>

        /// <param name="jsContent"></param>

        /// <returns></returns>

        public static bool CompressJsFile(string filePath, ref string jsContent)

        {

            bool ret = true;

            try

            {

                //目录不存在

                string[] pathList = filePath.Split(',');

                //获取该文件夹下所有js或者css文件

                HttpContext ctx = HttpContext.Current;

                string newDir = ctx.Server.MapPath("../scripts/");

                string filetype = ".min.js";

                string newFileName = GetNewFileName(filePath);

                string newFilePath = newDir + newFileName + filetype;

                if (File.Exists(newFilePath))

                {

                    FileInfo Nowinfo = new FileInfo(newFilePath);

                    jsContent = File.ReadAllText(Nowinfo.FullName, Encoding.UTF8);

                    return true;

                }

                foreach (string path in pathList)

                {

                    if (ctx.Server.MapPath(path) != "")

                    {

                        FileInfo info = new FileInfo(ctx.Server.MapPath(path));

                        string strContent = File.ReadAllText(info.FullName, Encoding.UTF8);

                        if (info.Extension.ToLower() == ".js")

                        {

                            if (!info.FullName.ToLower().EndsWith(".no.js"))

                            {

                                if (!info.FullName.ToLower().EndsWith(".min.js"))

                                {

                                    var js = new JavaScriptCompressor(strContent, false, Encoding.UTF8, System.Globalization.CultureInfo.CurrentCulture);

                                    strContent = js.Compress();

                                }

                                jsContent += "\n" + strContent;

                            }

                        }

                    }

                }

                var newFile = new FileInfo(newFilePath);

                File.WriteAllText(newFile.FullName, jsContent, Encoding.UTF8);

            }

            catch (Exception ex)

            { ret = false; }

            return ret;

        }


        /// <summary>

        /// 获取压缩后新文件的名称

        /// </summary>

        /// <param name="filePath"></param>

        /// <returns></returns>

        public static string GetNewFileName(string filePath)

        {

            string[] pathList = filePath.Split(',');

            //获取该文件夹下所有js或者css文件

            HttpContext ctx = HttpContext.Current;

            string newFileName = "";


            foreach (string path in pathList)

            {

                if (ctx.Server.MapPath(path) != "")

                {

                    FileInfo info = new FileInfo(ctx.Server.MapPath(path));

                    newFileName += info.Name.Replace(info.Extension, "") + "_";

                }

            }

            newFileName = newFileName.Remove(newFileName.Length - 1, 1);

            return newFileName;

        }

        #endregion


        #region 导入导出Excel


        /// <summary>

        /// 获取Excel文件数据表列表

        /// </summary>

        public static ArrayList GetExcelTables(string ExcelFileName)

        {

            DataTable dt = new DataTable();

            ArrayList TablesList = new ArrayList();

            if (File.Exists(ExcelFileName))

            {

                using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + ExcelFileName))

                {

                    try

                    {

                        conn.Open();

                        dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

                    }

                    catch (Exception exp)

                    {

                        throw exp;

                    }


                    //获取数据表个数

                    int tablecount = dt.Rows.Count;

                    for (int i = 0; i < tablecount; i++)

                    {

                        string tablename = dt.Rows[i][2].ToString().Trim().TrimEnd('$');

                        if (TablesList.IndexOf(tablename) < 0)

                        {

                            TablesList.Add(tablename);

                        }

                    }

                }

            }

            return TablesList;

        }

        #endregion


        #region 普通文件操作

        /// <summary>

        /// 备份文件

        /// </summary>

        /// <param name="sourceFileName">源文件名</param>

        /// <param name="destFileName">目标文件名</param>

        /// <param name="overwrite">当目标文件存在时是否覆盖</param>

        /// <returns>操作是否成功</returns>

        public static bool BackupFile(string sourceFileName, string destFileName, bool overwrite)

        {

            if (!System.IO.File.Exists(sourceFileName))

            {

                throw new FileNotFoundException(sourceFileName + "文件不存在!");

            }

            if (!overwrite && System.IO.File.Exists(destFileName))

            {

                return false;

            }

            try

            {

                System.IO.File.Copy(sourceFileName, destFileName, true);

                return true;

            }

            catch (Exception e)

            {

                throw e;

            }

        }

        #endregion


        #region 文件上传

        /// <summary>

        /// 是否允许该扩展名上传

        /// </summary>

        /// <param name="hifile"></param>

        /// <returns></returns>

        public static bool IsAllowedExtension(HtmlInputFile hifile)

        {

            string strOldFilePath = "", strExtension = "";


            //允许上传的扩展名,可以改成从配置文件中读出

            string[] arrExtension = { ".gif", ".GIF", ".JPG", ".jpg", ".JPEG", ".BMP", ".PNG", ".jpeg", ".bmp", ".png" };


            if (hifile.PostedFile.FileName != string.Empty)

            {

                strOldFilePath = hifile.PostedFile.FileName;

                //取得上传文件的扩展名

                strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));

                //判断该扩展名是否合法

                for (int i = 0; i < arrExtension.Length; i++)

                {

                    if (strExtension.Equals(arrExtension[i]))

                    {

                        return true;

                    }

                }

            }

            return false;

        }


        /// <summary>

        /// 判断上传文件大小是否超过最大值

        /// </summary>

        /// <param name="hifile"></param>

        /// <returns></returns>

        public static bool IsAllowedLength(HtmlInputFile hifile)

        {

            //允许上传文件大小的最大值,可以保存在xml文件中,单位为KB

            int i = 512;

            //如果上传文件的大小超过最大值,返回flase,否则返回true.

            if (hifile.PostedFile.ContentLength > i * 512)

            {

                return false;

            }

            return true;

        }

        /// <summary>

        /// 上传文件返回新文件名

        /// </summary>

        /// <param name="hifile"></param>

        /// <param name="strAbsolutePath"></param>

        /// <returns></returns>

        public static string SaveFile(HtmlInputFile hifile, string strAbsolutePath)

        {

            string strOldFilePath = "", strExtension = "", strNewFileName = "";


            if (hifile.PostedFile.FileName != string.Empty)

            {

                strOldFilePath = hifile.PostedFile.FileName;

                //取得上传文件的扩展名

                strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf("."));

                //文件上传后的命名

                strNewFileName = GetUniqueString() + strExtension;

                if (strAbsolutePath.LastIndexOf("\\") == strAbsolutePath.Length)

                {

                    hifile.PostedFile.SaveAs(strAbsolutePath + strNewFileName);

                }

                else

                {

                    hifile.PostedFile.SaveAs(strAbsolutePath + "\\" + strNewFileName);

                }

            }

            return strNewFileName;

        }

        /// <summary>

        /// 删除指定文件

        /// </summary>

        /// <param name="strAbsolutePath"></param>

        /// <param name="strFileName"></param>

        public static void DeleteFile(string strAbsolutePath, string strFileName)

        {

            if (strAbsolutePath.LastIndexOf("\\") == strAbsolutePath.Length)

            {

                if (File.Exists(strAbsolutePath + strFileName))

                {

                    File.Delete(strAbsolutePath + strFileName);

                }

            }

            else

            {

                if (File.Exists(strAbsolutePath + "\\" + strFileName))

                {

                    File.Delete(strAbsolutePath + "\\" + strFileName);

                }

            }

        }

        /// <summary>

        /// 删除文件夹下面的文件

        /// </summary>

        /// <param name="path"></param>

        public static void DeleteFilePath(string path)

        {

            string[] fileList = Directory.GetFiles(path);

            foreach (string str in fileList)

            {

                File.Delete(str);

            }

        }

        /// <summary>

        /// 获取不重复文件名

        /// </summary>

        /// <returns></returns>

        public static string GetUniqueString()

        {

            return DateTime.Now.ToString("yyyyMMddhhmmssff");

        }


        #endregion


        /// <summary> 

        /// 将 Stream 转成 byte[] 

        /// </summary> 

        public static byte[] StreamToBytes(Stream stream)

        {

            byte[] bytes = new byte[stream.Length];

            stream.Read(bytes, 0, bytes.Length);


            // 设置当前流的位置为流的开始 

            stream.Seek(0, SeekOrigin.Begin);

            return bytes;

        }


        /// <summary> 

        /// 将 byte[] 转成 Stream 

        /// </summary> 

        public static Stream BytesToStream(byte[] bytes)

        {

            Stream stream = new MemoryStream(bytes);

            return stream;

        }

    }

}