读取Excel模板,程序填上相应的内容,再进行下载输出给客瞳

/// <summary>
/// 技术变更打印模板
/// </summary>
/// <param name="OrderID">订单主键</param>
/// <returns></returns>
[CheckPower(ISPower = false, Name = "缺件打印模板")]
public IActionResult PrintOrderChanged_QueJain(int OrderID, int OcID)
{

#region 加工EXCEL
string File = "~/FileTemp/缺件打印模板.xlsx";
string FullPathFileName = PageContext.MapPath(File);
FileInfo newFile = new FileInfo(FullPathFileName);//文件模板流
using (ExcelPackage package = new ExcelPackage(newFile))//实例化Excel类时加载 导出文件模板
{
ExcelWorksheet worksheet = package.Workbook.Worksheets["缺件发货打印模板"]; //加载模板第一张表

var TOrderModel = db.TOrders.Where(x => x.rowguid == OrderID).FirstOrDefault();
string Item_no = TOrderModel.Item_no;
var CustomerModel = db.Customer.Where(x => x.CustomerID == TOrderModel.Custom_no).FirstOrDefault();
var TOrderChanageModel = db.TOrderChanage.Where(x => x.ID == OcID).FirstOrDefault();

if (TOrderChanageModel.REC_CREATE_TIME != null)
{
worksheet.Cells[4, 8].Value = ((DateTime)TOrderChanageModel.REC_CREATE_TIME).ToString("D"); //评审时间
}
//worksheet.Cells[5, 2].Style.ShrinkToFit = true;//自适应字体大小
worksheet.Cells[5, 3].Value = CustomerModel.CustomerName;//客户名称
worksheet.Cells[5, 8].Value = TOrderModel.Pro_name;//订单类型
worksheet.Cells[6, 3].Value = TOrderModel.Item_no;//项目编号
worksheet.Cells[6, 5].Value = TOrderModel.Item_name;//项目名称
worksheet.Cells[6, 5].Style.ShrinkToFit = true;//自适应字体大小
if (TOrderModel.Contract_delivered_time != null)
{
worksheet.Cells[6, 8].Value = ((DateTime)TOrderModel.Contract_delivered_time).ToString("D");//合同交期
}

//表格数据
var TOrderItemModel = db.TOrderItem.Where(x => x.OrderId == OrderID).OrderBy(x => x.OrderItemId);
if (TOrderItemModel.Count() > 0)
{
worksheet.InsertRow(8, TOrderItemModel.Count());//动态插入行
var list = TOrderItemModel.ToList();
for (int i = 0; i < TOrderItemModel.Count(); i++)
{
//string cellsArea = "B" + (8 + i) + " :C" + (8 + i);
//worksheet.Cells["B8:C8"].Merge = true;
worksheet.Cells["B" + (8 + i) + ":C" + (8 + i)].Merge = true;
worksheet.Cells[8 + i, 2].Value = list[i].Pro_title;//名称
worksheet.Cells[8 + i, 2].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//水平居中
worksheet.Cells[8 + i, 2].Style.Border.Left.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 2].Style.Border.Right.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 2].Style.Border.Top.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 2].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
//worksheet.Cells[8 + i, 1].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.FromArgb(191, 191, 191));//全边框

worksheet.Cells["D" + (8 + i) + ":E" + (8 + i)].Merge = true;
//worksheet.Cells["D8:E8"].Merge = true;
worksheet.Cells[8 + i, 4].Value = list[i].Pro_model;//型号
worksheet.Cells[8 + i, 4].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//水平居中
worksheet.Cells[8 + i, 4].Style.Border.Left.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 4].Style.Border.Right.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 4].Style.Border.Top.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 4].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;

worksheet.Cells[8 + i, 6].Value = list[i].Pro_unit;//单位
worksheet.Cells[8 + i, 6].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//水平居中
worksheet.Cells[8 + i, 6].Style.Border.Left.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 6].Style.Border.Right.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 6].Style.Border.Top.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 6].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;

worksheet.Cells[8 + i, 7].Value = list[i].Pro_number;//
worksheet.Cells[8 + i, 7].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//水平居中
worksheet.Cells[8 + i, 7].Style.Border.Left.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 7].Style.Border.Right.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 7].Style.Border.Top.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 7].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;

worksheet.Cells[8 + i, 8].Value = null;
worksheet.Cells[8 + i, 8].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;//水平居中
worksheet.Cells[8 + i, 8].Style.Border.Left.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 8].Style.Border.Right.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 8].Style.Border.Top.Style = ExcelBorderStyle.Thin;
worksheet.Cells[8 + i, 8].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
}
}

//获取项目处理节点信息
var dealNodel = from tdn in db.TTransDealNode
join tm in db.TTransMain on tdn.TMID equals tm.TMID
join fb in db.TFlowBase on tm.FBID equals fb.FBID
join ordchange in db.TOrderChanage on tm.MainComID equals ordchange.ID.ToString()
//join ord in db.TOrders on ordchange.OrderID equals ord.rowguid
join fnr in db.TFlowNodeRoperty on tdn.FNRID equals fnr.FNRID
join fn in db.TFlowNodes on fnr.FNID equals fn.FNID
join u in db.TUser on tdn.DealUser equals u.ROWGUID
where tdn.TDState == "正常" //&& ord.Item_no ==
&& ordchange.OrderID == TOrderModel.rowguid
select new
{
UserName = u.USER_NAME,//节点处理人
FNName = fn.FNName,//节点名称
FBID = tm.FBID,//流程类型
DealDate = tdn.DealDate,
DealDescription = tdn.DealDescription,//处理意见
FNID = fn.FNID
};
var changeDetail = dealNodel.Where(x => x.FNID == 232 && x.FBID == TOrderChanageModel.FBID)
.OrderByDescending(x => x.DealDate)
.FirstOrDefault().DealDescription;//申请
worksheet.Cells[8 + TOrderItemModel.Count(), 4].Value = "具体内容:" + changeDetail;//具体内容

var jdModel = dealNodel.Where(x => x.FNID == 233 && x.FBID == TOrderChanageModel.FBID)
.OrderByDescending(x => x.DealDate)
.FirstOrDefault();//计调确认
var swModel = dealNodel.Where(x => (x.FNID == 234) && x.FBID == TOrderChanageModel.FBID)
.OrderByDescending(x => x.DealDate)
.FirstOrDefault();//商务确认
var pgModel = dealNodel.Where(x => x.FNID == 235 && x.FBID == TOrderChanageModel.FBID)
.OrderByDescending(x => x.DealDate)
.FirstOrDefault();//品管确认
var jsModel = dealNodel.Where(x => x.FNID == 236 && x.FBID == TOrderChanageModel.FBID)
.OrderByDescending(x => x.DealDate)//常务副总审批
.FirstOrDefault();
if (jdModel != null)
{
//计调确认
worksheet.Cells[11 + TOrderItemModel.Count(), 4].Value = jdModel.DealDescription;//处理意见
worksheet.Cells[11 + TOrderItemModel.Count(), 7].Value = "签名:" + jdModel.UserName;//处理人
if (jdModel.DealDate != null)
{
worksheet.Cells[12 + TOrderItemModel.Count(), 7].Value = ((DateTime)jdModel.DealDate).ToString("D"); //处理日期
}
}
//品管确认
if (swModel != null)
{
worksheet.Cells[13 + TOrderItemModel.Count(), 4].Value = swModel.DealDescription;//处理意见
worksheet.Cells[13 + TOrderItemModel.Count(), 7].Value = "签名:" + swModel.UserName;//处理人
if (swModel.DealDate != null)
{
worksheet.Cells[14 + TOrderItemModel.Count(), 7].Value = ((DateTime)swModel.DealDate).ToString("D"); //处理日期
}
}
//品管确认
if (pgModel != null)
{
worksheet.Cells[15 + TOrderItemModel.Count(), 4].Value = pgModel.DealDescription;//处理意见
worksheet.Cells[15 + TOrderItemModel.Count(), 7].Value = "签名:" + pgModel.UserName;//处理人
if (pgModel.DealDate != null)
{
worksheet.Cells[16 + TOrderItemModel.Count(), 7].Value = ((DateTime)pgModel.DealDate).ToString("D"); //处理日期
}
}
//技术副总审批
if (jsModel != null)
{
worksheet.Cells[17 + TOrderItemModel.Count(), 4].Value = jsModel.DealDescription;//处理意见
worksheet.Cells[17 + TOrderItemModel.Count(), 7].Value = "签名:" + jsModel.UserName;//处理人
if (jsModel.DealDate != null)
{
worksheet.Cells[18 + TOrderItemModel.Count(), 7].Value = ((DateTime)jsModel.DealDate).ToString("D"); //处理日期
}
}

var data = package.GetAsByteArray();
var FileName = DateTime.Now.ToString("yyyyMMddHHmmssff") + Item_no + " 缺件打印模板" + ".xlsx";
DirFileHelp.CreateFile(SomConfig.UploadPath + FileName, data);
DirFileHelp.DownFile(SomConfig.UploadPath + FileName);
}
GC.Collect();
Alert.Show("导出成功!", MessageBoxIcon.Success);
return UIHelper.Result();
#endregion
}
}


//下面是用到的文件帮助类
using System;
using System.Text;
using System.IO;
using FineUICore;

namespace Som.Common
{
    /// <summary>                         
    ///创建人:王我
    ///日 期:2018/1/23
    ///描 述:文件文件夹操作类
    /// </summary>
    public static class DirFileHelp
    {
        #region 检测指定目录是否存在
        /// <summary>
        /// 检测指定目录是否存在
        /// </summary>
        /// <param name="directoryPath">目录的绝对路径</param>
        /// <returns></returns>
        public static bool IsExistDirectory(string directoryPath)
        {
            return Directory.Exists(directoryPath);
        }
        #endregion

        #region 检测指定文件是否存在,如果存在返回true
        /// <summary>
        /// 检测指定文件是否存在,如果存在则返回true。
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static bool IsExistFile(string filePath)
        {
            return File.Exists(filePath);
        }
        #endregion

        #region 获取指定目录中的文件列表
        /// <summary>
        /// 获取指定目录中所有文件列表
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>        
        public static string[] GetFileNames(string directoryPath)
        {
            //如果目录不存在,则抛出异常
            if (!IsExistDirectory(directoryPath))
            {
                throw new FileNotFoundException();
            }

            //获取文件列表
            return Directory.GetFiles(directoryPath);
        }
        #endregion

        #region 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法.
        /// <summary>
        /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法.
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>        
        public static string[] GetDirectories(string directoryPath)
        {
            try
            {
                return Directory.GetDirectories(directoryPath);
            }
            catch (IOException ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取指定目录及子目录中所有文件列表
        /// <summary>
        /// 获取指定目录及子目录中所有文件列表
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
        /// <param name="isSearchChild">是否搜索子目录</param>
        public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild)
        {
            //如果目录不存在,则抛出异常
            if (!IsExistDirectory(directoryPath))
            {
                throw new FileNotFoundException();
            }

            try
            {
                if (isSearchChild)
                {
                    return Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories);
                }
                else
                {
                    return Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
                }
            }
            catch (IOException ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 检测指定目录是否为空
        /// <summary>
        /// 检测指定目录是否为空
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>        
        public static bool IsEmptyDirectory(string directoryPath)
        {
            try
            {
                //判断是否存在文件
                string[] fileNames = GetFileNames(directoryPath);
                if (fileNames.Length > 0)
                {
                    return false;
                }

                //判断是否存在文件夹
                string[] directoryNames = GetDirectories(directoryPath);
                if (directoryNames.Length > 0)
                {
                    return false;
                }

                return true;
            }
            catch
            {
                //这里记录日志
                //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
                return true;
            }
        }
        #endregion

        #region 检测指定目录中是否存在指定的文件
        /// <summary>
        /// 检测指定目录中是否存在指定的文件,若要搜索子目录请使用重载方法.
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>        
        public static bool Contains(string directoryPath, string searchPattern)
        {
            try
            {
                //获取指定的文件列表
                string[] fileNames = GetFileNames(directoryPath, searchPattern, false);

                //判断指定文件是否存在
                if (fileNames.Length == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
                //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
            }
        }

        /// <summary>
        /// 检测指定目录中是否存在指定的文件
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param> 
        /// <param name="isSearchChild">是否搜索子目录</param>
        public static bool Contains(string directoryPath, string searchPattern, bool isSearchChild)
        {
            try
            {
                //获取指定的文件列表
                string[] fileNames = GetFileNames(directoryPath, searchPattern, true);

                //判断指定文件是否存在
                if (fileNames.Length == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
                //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
            }
        }
        #endregion

        #region 创建目录
        /// <summary>
        /// 创建目录
        /// </summary>
        /// <param name="dir">要创建的目录路径包括目录名</param>
        public static void CreateDir(string dir)
        {
            if (dir.Length == 0) return;
            if (!Directory.Exists( dir))
                Directory.CreateDirectory( dir);
        }
        #endregion

        #region 删除目录
        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="dir">要删除的目录路径和名称</param>
        public static void DeleteDir(string dir)
        {
            if (dir.Length == 0) return;
            if (Directory.Exists( dir))
                Directory.Delete( dir);
        }
        #endregion

        #region 删除文件
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="file">要删除的文件路径和名称</param>
        public static void DeleteFile(string file)
        {
            if (File.Exists( file))
                File.Delete( file);
        }
        #endregion

        #region 创建文件
        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="dir">带后缀的文件名</param>
        /// <param name="pagestr">文件内容</param>
        public static void CreateFile(string dir, string pagestr)
        {
            dir = dir.Replace("/", "\\");
            if (dir.IndexOf("\\") > -1)
                CreateDir(dir.Substring(0, dir.LastIndexOf("\\")));
            System.IO.StreamWriter sw = new System.IO.StreamWriter( dir, false, System.Text.Encoding.GetEncoding("GB2312"));
            sw.Write(pagestr);
            sw.Close();
        }
        #endregion

        #region 移动文件(剪贴--粘贴)
        /// <summary>
        /// 移动文件(剪贴--粘贴)
        /// </summary>
        /// <param name="dir1">要移动的文件的路径及全名(包括后缀)</param>
        /// <param name="dir2">文件移动到新的位置,并指定新的文件名</param>
        public static void MoveFile(string dir1, string dir2)
        {
            dir1 = dir1.Replace("/", "\\");
            dir2 = dir2.Replace("/", "\\");
            if (File.Exists(dir2))
            {
                File.Delete( dir2);

            }
            if (File.Exists(dir1))
                File.Move( dir1, dir2);
        }
        #endregion

        #region 复制文件
        /// <summary>
        /// 复制文件
        /// </summary>
        /// <param name="dir1">要复制的文件的路径已经全名(包括后缀)</param>
        /// <param name="dir2">目标位置,并指定新的文件名</param>
        public static void CopyFile(string dir1, string dir2)
        {
            dir1 = dir1.Replace("/", "\\");
            dir2 = dir2.Replace("/", "\\");
            if (File.Exists( dir1))
            {
                File.Copy(dir1, dir2, true);
            }
        }
        #endregion

        #region 根据时间得到目录名 / 格式:yyyyMMdd 或者 HHmmssff
        /// <summary>
        /// 根据时间得到目录名yyyyMMdd
        /// </summary>
        /// <returns></returns>
        public static string GetDateDir()
        {
            return DateTime.Now.ToString("yyyyMMdd");
        }

        #region 根据文件路径获取所在路径
        /// <summary>
        /// 根据文件路径获取所在路径
        /// </summary>
        /// <returns></returns>
        public static string GetDirectoryName( string filePath)
        {
         return  Path.GetDirectoryName(filePath);
        }
        /// <summary>
        /// 根据时间得到文件名HHmmssff
        /// </summary>
        /// <returns></returns>
        public static string GetDateFile()
        {
            return DateTime.Now.ToString("HHmmssff");
        }
        #endregion

        #region 复制文件夹
        /// <summary>
        /// 复制文件夹(递归)
        /// </summary>
        /// <param name="varFromDirectory">源文件夹路径</param>
        /// <param name="varToDirectory">目标文件夹路径</param>
        public static void CopyFolder(string varFromDirectory, string varToDirectory)
        {
            Directory.CreateDirectory(varToDirectory);

            if (!Directory.Exists(varFromDirectory)) return;

            string[] directories = Directory.GetDirectories(varFromDirectory);

            if (directories.Length > 0)
            {
                foreach (string d in directories)
                {
                    CopyFolder(d, varToDirectory + d.Substring(d.LastIndexOf("\\")));
                }
            }
            string[] files = Directory.GetFiles(varFromDirectory);
            if (files.Length > 0)
            {
                foreach (string s in files)
                {
                    File.Copy(s, varToDirectory + s.Substring(s.LastIndexOf("\\")), true);
                }
            }
        }
        #endregion

        #region 检查文件,如果文件不存在则创建
        /// <summary>
        /// 检查文件,如果文件不存在则创建  
        /// </summary>
        /// <param name="FilePath">路径,包括文件名</param>
        public static void ExistsFile(string FilePath)
        {
            //if(!File.Exists(FilePath))    
            //File.Create(FilePath);    
            //以上写法会报错,详细解释请看下文.........   
            if (!File.Exists(FilePath))
            {
                FileStream fs = File.Create(FilePath);
                fs.Close();
            }
        }
        #endregion

        #region 删除指定文件夹对应其他文件夹里的文件
        /// <summary>
        /// 删除指定文件夹对应其他文件夹里的文件
        /// </summary>
        /// <param name="varFromDirectory">指定文件夹路径</param>
        /// <param name="varToDirectory">对应其他文件夹路径</param>
        public static void DeleteFolderFiles(string varFromDirectory, string varToDirectory)
        {
            Directory.CreateDirectory(varToDirectory);

            if (!Directory.Exists(varFromDirectory)) return;

            string[] directories = Directory.GetDirectories(varFromDirectory);

            if (directories.Length > 0)
            {
                foreach (string d in directories)
                {
                    DeleteFolderFiles(d, varToDirectory + d.Substring(d.LastIndexOf("\\")));
                }
            }


            string[] files = Directory.GetFiles(varFromDirectory);

            if (files.Length > 0)
            {
                foreach (string s in files)
                {
                    File.Delete(varToDirectory + s.Substring(s.LastIndexOf("\\")));
                }
            }
        }
        #endregion

        #region 从文件的绝对路径中获取文件名( 包含扩展名 )
        /// <summary>
        /// 从文件的绝对路径中获取文件名( 包含扩展名 )
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static string GetFileName(string filePath)
        {
            //获取文件的名称
            FileInfo fi = new FileInfo(filePath);
            return fi.Name;
        }
        #endregion


        #region 创建一个目录
        /// <summary>
        /// 创建一个目录
        /// </summary>
        /// <param name="directoryPath">目录的绝对路径</param>
        public static void CreateDirectory(string directoryPath)
        {
            //如果目录不存在则创建该目录
            if (!IsExistDirectory(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
        }
        #endregion

        #region 创建一个文件
        /// <summary>
        /// 创建一个文件。
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        public static void CreateFile(string filePath)
        {
            try
            {
                //如果文件不存在则创建该文件
                if (!IsExistFile(filePath))
                {
                    //创建一个FileInfo对象
                    FileInfo file = new FileInfo(filePath);

                    //创建文件
                    FileStream fs = file.Create();

                    //关闭文件流
                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
                throw ex;
            }
        }
        #endregion
        /// <summary>
        /// 创建一个文件,并将字节流写入文件。
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        /// <param name="buffer">二进制流数据</param>
        public static void CreateFile(string filePath, byte[] buffer)
        {
            try
            {
                //如果文件不存在则创建该文件
                if (!IsExistFile(filePath))
                {
                    //创建一个FileInfo对象
                    FileInfo file = new FileInfo(filePath);

                    //创建文件
                    FileStream fs = file.Create();

                    //写入二进制流
                    fs.Write(buffer, 0, buffer.Length);

                    //关闭文件流
                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
                throw ex;
            }
        }
        #endregion

        #region 获取文本文件的行数
        /// <summary>
        /// 获取文本文件的行数
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static int GetLineCount(string filePath)
        {
            //将文本文件的各行读到一个字符串数组中
            string[] rows = File.ReadAllLines(filePath);

            //返回行数
            return rows.Length;
        }
        #endregion

        #region 获取一个文件的长度
        /// <summary>
        /// 获取一个文件的长度,单位为Byte
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static int GetFileSize(string filePath)
        {
            //创建一个文件对象
            FileInfo fi = new FileInfo(filePath);

            //获取文件的大小
            return (int)fi.Length;
        }
        #endregion

        #region 获取指定目录中的子目录列表
        /// <summary>
        /// 获取指定目录及子目录中所有子目录列表
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
        /// <param name="isSearchChild">是否搜索子目录</param>
        public static string[] GetDirectories(string directoryPath, string searchPattern, bool isSearchChild)
        {
            try
            {
                if (isSearchChild)
                {
                    return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.AllDirectories);
                }
                else
                {
                    return Directory.GetDirectories(directoryPath, searchPattern, SearchOption.TopDirectoryOnly);
                }
            }
            catch (IOException ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 向文本文件写入内容

        /// <summary>
        /// 向文本文件中写入内容
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        /// <param name="text">写入的内容</param>
        /// <param name="encoding">编码</param>
        public static void WriteText(string filePath, string text, Encoding encoding)
        {
            //向文件写入内容
            File.WriteAllText(filePath, text, encoding);
        }
        #endregion

        #region 向文本文件的尾部追加内容
        /// <summary>
        /// 向文本文件的尾部追加内容
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        /// <param name="content">写入的内容</param>
        public static void AppendText(string filePath, string content)
        {
            File.AppendAllText(filePath, content);
        }
        #endregion

        #region 将现有文件的内容复制到新文件中
        /// <summary>
        /// 将源文件的内容复制到目标文件中
        /// </summary>
        /// <param name="sourceFilePath">源文件的绝对路径</param>
        /// <param name="destFilePath">目标文件的绝对路径</param>
        public static void Copy(string sourceFilePath, string destFilePath)
        {
            File.Copy(sourceFilePath, destFilePath, true);
        }
        #endregion

        #region 将文件移动到指定目录
        /// <summary>
        /// 将文件移动到指定目录
        /// </summary>
        /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>
        /// <param name="descDirectoryPath">移动到的目录的绝对路径</param>
        public static void Move(string sourceFilePath, string descDirectoryPath)
        {
            //获取源文件的名称
            string sourceFileName = GetFileName(sourceFilePath);

            if (IsExistDirectory(descDirectoryPath))
            {
                //如果目标中存在同名文件,则删除
                if (IsExistFile(descDirectoryPath + "\\" + sourceFileName))
                {
                    DeleteFile(descDirectoryPath + "\\" + sourceFileName);
                }
                //将文件移动到指定目录
                File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFileName);
            }
        }
        #endregion


        #region 从文件的绝对路径中获取文件名( 不包含扩展名 )
        /// <summary>
        /// 从文件的绝对路径中获取文件名( 不包含扩展名 )
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static string GetFileNameNoExtension(string filePath)
        {
            //获取文件的名称
            FileInfo fi = new FileInfo(filePath);
            return fi.Name.Split('.')[0];
        }
        #endregion

        #region 从文件的绝对路径中获取扩展名
        /// <summary>
        /// 从文件的绝对路径中获取扩展名
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static string GetExtension(string filePath)
        {
            //获取文件的名称
            FileInfo fi = new FileInfo(filePath);
            return fi.Extension;
        }
        #endregion

        #region 清空指定目录
        /// <summary>
        /// 清空指定目录下所有文件及子目录,但该目录依然保存.
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        public static void ClearDirectory(string directoryPath)
        {
            if (IsExistDirectory(directoryPath))
            {
                //删除目录中所有的文件
                string[] fileNames = GetFileNames(directoryPath);
                for (int i = 0; i < fileNames.Length; i++)
                {
                    DeleteFile(fileNames[i]);
                }

                //删除目录中所有的子目录
                string[] directoryNames = GetDirectories(directoryPath);
                for (int i = 0; i < directoryNames.Length; i++)
                {
                    DeleteDirectory(directoryNames[i]);
                }
            }
        }
        #endregion

        #region 清空文件内容
        /// <summary>
        /// 清空文件内容
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        public static void ClearFile(string filePath)
        {
            //删除文件
            File.Delete(filePath);

            //重新创建该文件
            CreateFile(filePath);
        }
        #endregion

        #region 删除指定目录
        /// <summary>
        /// 删除指定目录及其所有子目录
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        public static void DeleteDirectory(string directoryPath)
        {
            if (IsExistDirectory(directoryPath))
            {
                Directory.Delete(directoryPath, true);
            }
        }
        #endregion
        /// <summary>
        /// 判断文件哈希码是否相同
        /// </summary>
        /// <param name="sourceFilePath"></param>
        /// <param name="destFilePath"></param>
        /// <returns></returns>
        public static bool CompareFile(string sourceFilePath, string destFilePath)
        {

            //计算第一个文件的哈希值
            var hash = System.Security.Cryptography.HashAlgorithm.Create();
            var stream_1 = new System.IO.FileStream(sourceFilePath, System.IO.FileMode.Open);
            byte[] hashByte_1 = hash.ComputeHash(stream_1);
            stream_1.Close();
            //计算第二个文件的哈希值
            var stream_2 = new System.IO.FileStream(destFilePath, System.IO.FileMode.Open);
            byte[] hashByte_2 = hash.ComputeHash(stream_2);
            stream_2.Close();

            //比较两个哈希值
            if (BitConverter.ToString(hashByte_1) == BitConverter.ToString(hashByte_2))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 判断是否要覆盖
        /// </summary>
        /// <param name="sourceFilePath"></param>
        /// <param name="destFilePath"></param>
        /// <returns></returns>
        public static bool IsFile(string sourceFilePath, string destFilePath)
        {
            if (!IsExistFile(destFilePath))
            {
                return false;
            }
            else
            {
                return CompareFile(sourceFilePath, destFilePath);
            }
        }

        /// <summary>
        /// 将文件转换为byte数组
        /// </summary>
        /// <param name="path">文件地址</param>
        /// <returns>转换后的byte数组</returns>
        public static byte[] File2Bytes(string path)
        {
            if (!System.IO.File.Exists(path))
            {
                return new byte[0];
            }

            FileInfo fi = new FileInfo(path);
            byte[] buff = new byte[fi.Length];

            FileStream fs = fi.OpenRead();
            fs.Read(buff, 0, Convert.ToInt32(fs.Length));
            fs.Close();

            return buff;
        }

        /// <summary>
        /// 下载附件
        /// </summary>
        /// <param name="File"></param>
        public static void DownFile(string File)
        {
            string Fileurl = File.Replace("///", "/").Replace('\\', '/');
            if (!DirFileHelp.IsExistFile(Fileurl))
            {
                Alert.Show("附件异常,请联系系统管理员!"+Fileurl, MessageBoxIcon.Error);
                return ;
            }
            PageContext.RegisterStartupScript("window.location.href='/Home/DownLoad?file=" + Fileurl.Replace("#", "%23").Replace("&", "%26").Replace("=", "%3D").Replace("+", "%2B") + "';");
        }
    }
}

 

posted @ 2020-04-07 08:48  咖啡无眠  阅读(326)  评论(0编辑  收藏  举报