C#文件处理(上传、导入)

6 篇文章 0 订阅
using System;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Reflection;
using System.Web;

using log4net;
using Excel = Microsoft.Office.Interop.Excel;

namespace TMS.IMEX
{
    public class IMEXImportBase
    {
        private static readonly ILog m_log = LogManager.GetLogger(typeof(IMEXImportBase));

        #region 处理上传的文件
        /// <summary>
        /// 处理上传的文件
        /// </summary>
        /// <param name="fileData"></param>
        /// <returns></returns>
        protected string ProcessUploadFile(HttpPostedFileBase fileData)
        {
            m_log.Debug("IMEXImportBase->ProcessUploadFile Start");

            try
            {
                // 绝对路径文件名
                string fullFileName = string.Empty;

                // 原始文件名
                string oldFilename = Path.GetFileNameWithoutExtension(fileData.FileName);

                // 获得文件扩展名
                string fileExtension = Path.GetExtension(fileData.FileName);

                // 新文件名
                string newFileName = oldFilename + "_" + DateTime.Now.ToString("yyyyMMddHHmmssffffff") + fileExtension;

                // 保存的物理路径
                string phyPath = ConfigurationSettings.AppSettings["uploadFilePath"];

                // 如果物理路径不存在,则创建路径
                if (!Directory.Exists(phyPath))
                {
                    Directory.CreateDirectory(phyPath);
                }

                fullFileName = phyPath + "\\" + newFileName;

                fileData.SaveAs(fullFileName);

                return fullFileName;
            }
            catch (Exception ex)
            {
                m_log.Error("IMEXImportBase->ProcessUploadFile Error:", ex);
                throw new Exception(ex.Message);
            }
            finally
            {
                m_log.Debug("IMEXImportBase->ProcessUploadFile End");
            }

        }

        #endregion

        #region 读取Excel数据
        /// <summary>
        /// 读取Excel数据
        /// </summary>
        /// <param name="fullFileName"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        protected DataTable ReadExcelData(string fullFileName, string sheetName)
        {
            m_log.Debug("IMEXImportBase->ReadExcelData Start");
            string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;IMEX=1';" + "data source=" + fullFileName;

            OleDbConnection conn = new OleDbConnection(connStr);
            OleDbDataAdapter odda = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);

            DataSet ds = new DataSet();
            odda.Fill(ds, sheetName);

            m_log.Debug("IMEXImportBase->ReadExcelData End");
            return ds.Tables[sheetName];
        }

        #endregion

        #region 读取Excel数据
        /// <summary>
        /// 读取Excel数据
        /// </summary>
        /// <param name="fullFileName"></param>
        /// <returns></returns>
        protected object[,] ReadExcelData(string fullFileName)
        {
            Excel.Application app = null;
            Excel.Workbook book = null;
            Excel.Worksheet sheet = null;
            try
            {
                m_log.Debug("IMEXImportBase->ReadExcelData Start");
                app = new Excel.Application();
                book =
                   (Excel.Workbook)
                   app.Workbooks.Open(fullFileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                      Type.Missing, Type.Missing,
                                      Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                      Type.Missing, Type.Missing, Type.Missing);

                sheet = (Excel.Worksheet)book.Sheets[1];

                var data = sheet.UsedRange.Value[Missing.Value] as object[,];

                return data;
            }
            catch (Exception ex)
            {
                m_log.Error("IMEXExportBase->ReadExcelData" + ex.Message);
                throw new Exception("IMEXExportBase->ReadExcelData():Failed", ex);
            }
            finally
            {
                //关闭Excel进程
                if (sheet != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
                }
                if (book != null)
                {
                    book.Close(false, Missing.Value, Missing.Value);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
                }
                if (app != null)
                {
                    app.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                }
                GC.Collect();

                m_log.Debug("IMEXImportBase->ReadExcelData End");
            }
        }

        #endregion

        #region 处理上传的文件
        /// <summary>
        /// 处理上传的文件
        /// </summary>
        /// <param name="fileData"></param>
        /// <param name="fileName">保存的文件名</param>
        /// <param name="phyPath">保存的物理路径</param>
        /// <returns></returns>
        protected string ProcessUploadImg(HttpPostedFileBase fileData, string fileName, string phyPath)
        {
            m_log.Debug("IMEXImportBase->ProcessUploadImg Start");

            try
            {
                // 获得文件扩展名
                string fileExtension = Path.GetExtension(fileData.FileName);

                // 新文件名
                string newFileName = fileName + fileExtension;

                // 如果物理路径不存在,则创建路径
                if (!Directory.Exists(phyPath))
                {
                    Directory.CreateDirectory(phyPath);
                }

                // 绝对路径文件名
                string fullFileName = phyPath + "\\" + newFileName;

                // 删除文件
                DeleteFile(phyPath, fileName);

                fileData.SaveAs(fullFileName);

                return fullFileName;
            }
            catch (Exception ex)
            {
                m_log.Error("IMEXImportBase->ProcessUploadImg Error:", ex);
                throw new Exception(ex.Message);
            }
            finally
            {
                m_log.Debug("IMEXImportBase->ProcessUploadImg End");
            }

        }
        #endregion

        #region 删除文件
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public void DeleteFile(string filePath, string fileName)
        {
            var directory = new DirectoryInfo(@filePath);
            var files = directory.GetFiles(fileName + ".*");
            foreach (var file in files)
            {
                file.Delete();
            }
        }
        #endregion

    }
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 文件处理技术,包括file,fileinfo等,具体如下 第三章 文件处理技术 2 3-1 System.IO 命名空间 2 3-1-1 System.IO类介绍 2 3-1-2 File类的常用方法 4 3-1-3 Fileinfo类的常用方法 5 3-1 Fileinfo类的常用方法 5 1.案例学习:了解FileInfo类的一些主要属性 6 2.案例学习:实现文件的复制 6 3.案例学习:获取文件基本信息 8 3-2 文件夹类Directory的常用方法 10 1.案例学习:了解Directory类的一些主要方法 10 2.案例学习:获取文件的基本信息 11 3-3 File类的常用操作的静态方法练习 14 1.案例学习:简易文本编辑器的开发案例 15 3-4 文件流类FileStream 17 1.FileStream文件流类简介 17 2.FileStream文件流类的创建 18 3-4 文件读写例子 20 3-3-1案例学习:文件流FileStream综合案例(一) 20 3-5 文件流FileStream综合案例 30 3-3-2 案例学习:文件流FileStream综合案例(二) 30 3-6 读写二进制文件 33 3-6-1 二进制文件读取器/编写器介绍 33 3-7 写二进制文件案例学习 35 1. 案例学习:写二进制文件案例——图片的存储与复制 35 3-8 读写内存流 39 3-8-1 读写内存流——MemoryStream类 40 3-8-2 MemoryStream类案例学习 41 3-8-3 读写缓存流——BufferedStream类 43 3-9 读写缓存流 ——BufferedStream类 43 3-9-1 读写缓存流 ——BufferedStream类 43 3-9-2 BufferedStream类案例学习 43 1.案例学习:通过缓冲区交换数据 43 3-6本章小结 45

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值