| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666 |
- using Aliyun.OSS;
- using Aliyun.OSS.Common;
- using BizCom;
- using ICSharpCode.SharpZipLib.Zip;
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Diagnostics;
- using System.IO;
- using System.IO.Compression;
- using System.Runtime.InteropServices;
- using System.Security.Principal;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Web;
- public partial class supplierBuildFile : System.Web.UI.Page
- {
- public static string upPath = ConfigurationManager.AppSettings["upPath"];
- public static string copyPath = ConfigurationManager.AppSettings["copyPath"];
- public static string siteUrl = ConfigurationManager.AppSettings["OriSiteUrl"];
- [DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
- public static extern uint DecFile(string filename);
- [DllImport("DrvInterface64.dll", CharSet = CharSet.Unicode)]
- public static extern int IsFileEncrypted(string filename);//返回1为加密,0为未被加密
- [DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
- public static extern void CreateUserKey(StringBuilder key, int len);
- [DllImport("DrvInterface64.dll", CharSet = CharSet.Ansi)]
- public static extern int InitAesKey(StringBuilder key, int len);
- [DllImport("DrvInterface64.dll")]
- public static extern int IsInitedAesKey();
- private void conErc(string msg)
- {
- XLog.SaveLog(0, msg);
- Response.Write(msg);
- //Response.StatusCode = (int)HttpStatusCode.NotFound;
- //Response.End();
- }
- private void conSuc(string msg)
- {
- Response.Write("{\"type\":\"success\",\"result\":\"" + msg + "\"}");
- //Response.End();
- }
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- Response.Buffer = true;
- downloadMore();
- }
- }
- private string getCanDownFile(string fileName)
- {
- string[] extArr = new string[] { ".cdr", ".zip", ".rar", ".pdf" };
- foreach (string ext in extArr)
- {
- string fname = fileName + ext;
- if (File.Exists(fname))
- {
- return ext;
- }
- }
- return "";
- }
- static bool running = false;
- private void downloadMore()
- {
- if (running)
- {
- conSuc("运行中!");
- return;
- }
- running = true;
- var identity = WindowsIdentity.GetCurrent();
- var principal = new WindowsPrincipal(identity);
- Task.Run(async () =>
- {
- using (identity.Impersonate())
- {
- StringBuilder sql = new StringBuilder();
- sql.AppendFormat("select * from CE_ErpPackData WITH(nolock) where upStatus = 0");
- int userId = 1;
- DataTable dt = CeErpTradeCell.ExecuteDataset(sql.ToString()).Tables[0];
- string updateSql = "";
- if (dt != null && dt.Rows.Count > 0)
- {
- foreach (DataRow dr in dt.Rows)
- {
- string zipFileName = dr["fileName"].ToString();
- int supplierId = 0;
- string packId = dr["ID"].ToString();
- try
- {
- CeErpTradeLog.ExecuteNonQuery(string.Format("update CE_ErpPackData set upStatus = 1 where ID= {0} ;", packId));
- DataTable itemData = CeErpTradeCell.ExecuteDataset(string.Format("select ctid,seller_memo,FinishDesignTime,OrderState,SupplierName,OrderSn,tid,SupplierId from view_erptradecell where FinishDesignTime is not null and ctid in (SELECT ctid FROM CE_ErpPackDataItem WHERE packId = {0})", packId)).Tables[0];
- List<string> files = new List<string>();
- List<string> tids = new List<string>();
- int upStatus = 3;
- string url = "";
- if (itemData != null && itemData.Rows.Count > 0)
- {
- string suppierName = "";
- foreach (DataRow row in itemData.Rows)
- {
- supplierId = Convert.ToInt32(row["SupplierId"].ToString());
- string finishDesignTime = getDesignTime(row["FinishDesignTime"]);
- string ctid = row["ctid"].ToString();
- string df_name = upPath + "\\" + finishDesignTime + "\\" + formatMemo(row["seller_memo"]);
- string ext = getCanDownFile(df_name);
- suppierName = row["SupplierName"].ToString();
- if (string.IsNullOrEmpty(ext))
- {
- //不存在则打包失败
- updateSql += string.Format("update CE_ErpPackDataItem set message = '文件不存在!' where packId= {0} and ctid='{1}' ;", packId, ctid);
- files = new List<string>();
- supplierId = 0;
- break;
- }
- string fname = df_name + ext;
- if (Convert.ToInt16(row["OrderState"]) != 6)
- {
- updateSql += string.Format("update CE_ErpPackDataItem set message = '订单状态不正确!' where packId= {0} and ctid='{1}' ;", packId, ctid);
- continue;
- }
- int IsFileEncrypt = IsFileEncrypted(fname);
- if (IsFileEncrypt == 1 && File.Exists(fname))
- {
- string key = "gBQnlxiBb7MthH9644V0W0pFwqYZgyy7";
- var sb = new StringBuilder(key);
- //Linux系统的接口要调用一次,Windows系统要调用两次
- CreateUserKey(sb, key.Length);
- CreateUserKey(sb, key.Length); //破解用dse生成的文件,需要调2次。
- int result = InitAesKey(sb, sb.Length);
- result = IsInitedAesKey();
- if (result != 1)
- {
- addLog(ctid, userId, "初始化秘钥失败" + result, 0);
- updateSql += string.Format("update CE_ErpPackDataItem set message = '解密失败!' where packId= {0} and ctid='{1}' ;", packId, ctid);
- continue;
- }
- uint a = DecFile(fname);
- if (a != 0)
- {
- addLog(ctid, userId, "解密失败" + a, 0);
- updateSql += string.Format("update CE_ErpPackDataItem set message = '解密失败!' where packId= {0} and ctid='{1}' ;", packId, ctid);
- continue;
- }
- }
- if (string.IsNullOrEmpty(fname))
- {
- updateSql += string.Format("update CE_ErpPackDataItem set message = '解密失败!' where packId= {0} and ctid='{1}' ;", packId, ctid);
- continue;
- }
- try
- {
- copyFile(getDesignDate(row["FinishDesignTime"]), suppierName, fname, zipFileName.Replace(".zip", ""));
- files.Add(fname);
- supplierId = 0;
- tids.Add("'" + ctid + "'");
- }
- catch (Exception ex)
- {
- writeLog("打包复制文件出错!" + ex.Message);
- updateSql += string.Format("update CE_ErpPackDataItem set message = '复制文件出错!{2}' where packId= {0} and ctid='{1}' ;", packId, ctid, ex.Message);
- files = new List<string>();//清空数据
- supplierId = 0;
- break;
- }
- }
- if (files.Count == 0)
- {
- updateSql += string.Format("update CE_ErpPackData set upStatus = 3,message='没有可打包文件!' where ID= {0} ;", packId);
- continue;
- }
- else
- {
- string sourceFolder = getCopyPath(getDesignDate(""), suppierName, zipFileName.Replace(".zip", ""));
- string zipFilePath = getCopyPath(getDesignDate(""), suppierName) + "\\" + zipFileName;
- ZipLargeFolder(sourceFolder, zipFilePath, supplierId);
- url = FileOssUpV2(zipFilePath, zipFileName);
- if (url != null)
- {
- upStatus = 2;
- updateSql += string.Format("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", string.Join(",", tids), (int)OrderState.下单完成, 0, "下载设计文件");
- updateSql += string.Format("update ce_erptradecell set UpdateTime=getdate() where ctid in ({0}) ;", string.Join(",", tids));
- }
- }
- }
- updateSql += string.Format("update CE_ErpPackData set upStatus = {1},fileUrl='{2}' where ID= {0} ;", packId, upStatus, url);
- }
- catch (Exception ex)
- {
- writeLog("打包文件出错!" + ex.Message);
- updateSql += string.Format("update CE_ErpPackData set upStatus = 3 where ID= {0} ;", packId);
- }
- CeErpTradeLog.ExecuteNonQuery(updateSql);
- updateSql = "";
- }
- }
- running = false;
- }
- });
- conSuc("运行结束!");
- //FileOssUp();
- }
- private static string dealMemoName(string name)
- {
- string[] al = name.Split('-');
- List<string> list = new List<string>();
- string pa = string.Empty;
- for (int i = 0; i < al.Length; i++)
- {
- if (i == 1)
- {
- if (al[i].Contains("(") || al[i].Contains("("))
- {
- string tname = al[i].Replace(")", "").Replace(")", "").Replace("(", "").Replace("(", "");
- if (!string.IsNullOrEmpty(tname))
- {
- pa = al[i];
- }
- continue;
- }
- }
- list.Add(al[i]);
- }
- if (!string.IsNullOrEmpty(pa))
- {
- list.Insert(3, pa);
- }
- name = string.Join("-", list);
- return name;
- }
- private string formatMemo(object memo)
- {
- string m = memo.ToString();
- m = m.Replace("\\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace("<", "").Replace(">", "").Replace("|", "");
- return m;
- }
- private void copyFile(string date, string supplier, string file, string zipName = "")
- {
- string path = getCopyPath(date, supplier, zipName);
- if (!Directory.Exists(path)) Directory.CreateDirectory(path);
- string fname = Path.GetFileName(file);
- File.Copy(file, path + "\\" + fname, true);
- if (!File.Exists(path + "\\" + fname))
- {
- File.Copy(file, path + "\\" + fname, true);
- }
- }
- private string getCopyPath(string date, string supplier, string zipName = "")
- {
- string path = copyPath + "\\" + date + "\\" + supplier + "\\" + "车间下载";
- if (!string.IsNullOrEmpty(zipName))
- {
- path = path + "\\" + zipName;
- }
- return path;
- }
- private string getDesignTime(object v)
- {
- if (v.ToString() == "") return "";
- return Convert.ToDateTime(v).ToString("yyyyMMdd");
- }
- private string getDesignDate(object v)
- {
- int year = DateTime.Now.Year;
- int month = DateTime.Now.Month;
- int day = DateTime.Now.Day;
- return year + "\\" + month + "\\" + day;
- /*if (v.ToString() == "") return "";
- return Convert.ToDateTime(v).ToString("yyyy-MM-dd");*/
- }
- private string FileOssUp(byte[] buffer, string fileName)
- {
- // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
- var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
- // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
- var accessKeyId = "LTAI5tE7wuNkeT9jZ42bQnyr";
- var accessKeySecret = "NnutvWhKl4HbQFSad3HosYbCkEkbjN";
- // 填写Bucket名称,例如examplebucket。
- var bucketName = "ltcloudfile";
- int year = DateTime.Now.Year;
- int month = DateTime.Now.Month;
- int day = DateTime.Now.Day;
- // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
- var objectName = "supplierFile/" + year + "/" + month + "/" + day + "/" + fileName;
- // 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。
- string region = "cn-hangzhou";
- // 创建ClientConfiguration实例,按照您的需要修改默认参数。
- var conf = new ClientConfiguration();
- // 设置v4签名。
- conf.SignatureVersion = SignatureVersion.V4;
- // 创建OssClient实例。
- var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
- client.SetRegion(region);
- try
- {
- MemoryStream requestContent = new MemoryStream(buffer);
- // 上传文件。
- client.PutObject(bucketName, objectName, requestContent);
- }
- catch (Exception ex)
- {
- writeLog("打包文件上传oss出错!" + ex.Message);
- return null;
- }
- return "https://ltcloudfile.oss-cn-hangzhou.aliyuncs.com/" + objectName;
- }
- private string FileOssUpV2(string filePath, string fileName)
- {
- // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
- var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
- // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
- var accessKeyId = "LTAI5tE7wuNkeT9jZ42bQnyr";
- var accessKeySecret = "NnutvWhKl4HbQFSad3HosYbCkEkbjN";
- // 填写Bucket名称,例如examplebucket。
- var bucketName = "ltcloudfile";
- int year = DateTime.Now.Year;
- int month = DateTime.Now.Month;
- int day = DateTime.Now.Day;
- // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
- var objectName = "supplierFile/" + year + "/" + month + "/" + day + "/" + fileName;
- // 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。
- string region = "cn-hangzhou";
- // 创建ClientConfiguration实例,按照您的需要修改默认参数。
- var conf = new ClientConfiguration();
- // 设置v4签名。
- conf.SignatureVersion = SignatureVersion.V4;
- // 创建OssClient实例。
- var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
- client.SetRegion(region);
- var uploadId = "";
- try
- {
- // 定义上传的文件及所属Bucket的名称。您可以在InitiateMultipartUploadRequest中设置ObjectMeta,但不必指定其中的ContentLength。
- var request = new InitiateMultipartUploadRequest(bucketName, objectName);
- var result = client.InitiateMultipartUpload(request);
- uploadId = result.UploadId;
- }
- catch (Exception ex)
- {
- writeLog("Init multi part upload failed, {0}" + ex.Message);
- Environment.Exit(1);
- }
- // 计算分片总数。
- // 分片最小值为100 KB,最大值为5 GB。最后一个分片的大小允许小于100 KB。
- var partSize = 10 * 1024 * 1024;
- var fi = new FileInfo(filePath);
- var fileSize = fi.Length;
- var partCount = fileSize / partSize;
- if (fileSize % partSize != 0)
- {
- partCount++;
- }
- var partETags = new List<PartETag>();
- try
- {
- using (var fs = File.Open(filePath, FileMode.Open))
- {
- for (var i = 0; i < partCount; i++)
- {
- var skipBytes = (long)partSize * i;
- // 定位到本次上传的起始位置。
- fs.Seek(skipBytes, 0);
- // 计算本次上传的分片大小,最后一片为剩余的数据大小。
- var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes);
- var request = new UploadPartRequest(bucketName, objectName, uploadId)
- {
- InputStream = fs,
- PartSize = size,
- PartNumber = i + 1
- };
- // 调用UploadPart接口执行上传功能,返回结果中包含了这个数据片的ETag值。
- var result = client.UploadPart(request);
- partETags.Add(result.PartETag);
- writeLog(string.Format(fileName + ":finish {0}/{1}", partETags.Count, partCount));
- }
- writeLog(string.Format(fileName + ":Put multi part upload succeeded"));
- }
- }
- catch (Exception ex)
- {
- writeLog(string.Format("Put multi part upload failed, {0}", ex.Message));
- Environment.Exit(1);
- }
- // 当分片上传成功后,合并分片。
- try
- {
- var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId);
- foreach (var partETag in partETags)
- {
- completeMultipartUploadRequest.PartETags.Add(partETag);
- }
- var result = client.CompleteMultipartUpload(completeMultipartUploadRequest);
- }
- catch (Exception ex)
- {
- writeLog(string.Format("complete multi part failed, {0}", ex.Message));
- Environment.Exit(1);
- }
- return "https://ltcloudfile.oss-cn-hangzhou.aliyuncs.com/" + objectName;
- }
- /// 批量进行多个文件压缩到一个文件
- /// </summary>
- /// <param name="files">文件列表(绝对路径)</param> 这里用的数组,你可以用list 等或者
- /// <param name="zipFileName">生成的zip文件名称</param>
- private void ZipFileDownload(int userId, List<string> ctidLst, List<string> files, string zipFileName, int onlyDownFile, int isFromClient)
- {
- // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
- var endpoint = "https://oss-cn-fuzhou.aliyuncs.com";
- // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
- var accessKeyId = "LTAI5tE7wuNkeT9jZ42bQnyr";
- var accessKeySecret = "NnutvWhKl4HbQFSad3HosYbCkEkbjN";
- // 填写Bucket名称,例如examplebucket。
- var bucketName = "dfdiyfile";
- // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
- var objectName = "exampledir/exampleobject.txt";
- // 填写字符串。
- var objectContent = "More than just cloud.";
- // 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。
- const string region = "oss-cn-fuzhou";
- // 创建ClientConfiguration实例,按照您的需要修改默认参数。
- var conf = new ClientConfiguration();
- // 设置v4签名。
- conf.SignatureVersion = SignatureVersion.V4;
- // 创建OssClient实例。
- var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
- client.SetRegion(region);
- try
- {
- MemoryStream ms = new MemoryStream();
- byte[] buffer = null;
- using (ZipFile file = ZipFile.Create(ms))
- {
- file.BeginUpdate();
- //file.NameTransform = new ZipNameTransform();
- file.NameTransform = new MyNameTransfom();
- file.Add("C:\\Users\\231010\\Downloads\\setup.exe");
- file.CommitUpdate();
- buffer = new byte[ms.Length];
- ms.Position = 0;
- ms.Read(buffer, 0, buffer.Length); //读取文件内容(1次读ms.Length/1024M)
- ms.Flush();
- ms.Close();
- }
- MemoryStream requestContent = new MemoryStream(buffer);
- // 上传文件。
- client.PutObject(bucketName, objectName, requestContent);
- Console.WriteLine("Put object succeeded");
- }
- catch (Exception ex)
- {
- Console.WriteLine("Put object failed, {0}", ex.Message);
- }
- conSuc("上传成功!");
- return;
- //for (int i = 0; i < addFiles.Count; i++)
- //{
- // updateIsDownSuccess(userId, addCtid[i]);
- //}
- //StringBuilder sql = new StringBuilder();
- //string tids = string.Join(",", addCtid);
- //sql.AppendFormat("update CE_ErpTradeCell set OrderState = 6 where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"));
- //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
- //sql = new StringBuilder();
- //sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"), (int)OrderState.下单完成, userId, "下载设计文件");
- //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
- }
- //public static object downfileObj = new object();
- private void downLoadFile(int userId, string ctid, string file, int onlyDownFile, int isFromClient)
- {
- string filePath = file;
- string dfile = Path.GetFileName(file);
- FileStream fs = new FileStream(filePath, FileMode.Open);
- byte[] bytes = new byte[(int)fs.Length];
- fs.Read(bytes, 0, bytes.Length);
- fs.Close();
- Response.Clear();
- //
- Response.ClearContent();
- Response.ClearHeaders();
- Response.ContentType = "application/octet-stream";
- //通知浏览器下载文件而不是打开\\fileDownload=true; path=/
- Response.AddHeader("Set-Cookie", "fileDownload=true; path=/;");
- //Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
- Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(dfile, System.Text.Encoding.UTF8));
- Response.AddHeader("Content-Length", bytes.Length.ToString());
- Response.AddHeader("Access-Control-Expose-Headers", "Content-Disposition");
- Response.BinaryWrite(bytes);
- Response.Flush();
- //updateIsDownSuccess(userId, ctid);
- //StringBuilder sql = new StringBuilder();
- //string tids = string.Join(",", ctid);
- //sql.AppendFormat("update CE_ErpTradeCell set OrderState = 6 where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"));
- //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
- //sql = new StringBuilder();
- //sql.AppendFormat("insert into CE_ErpTradeLog(tid,orderstate,userid,operatetime,con) select ctid,{1},{2},getdate(),'{3}' from ce_erptradecell where ctid in ({0}) ;", ("'" + tids.Replace(",", "','") + "'"), (int)OrderState.下单完成, userId, "下载设计文件");
- //CeErpTradeCell.ExecuteNonQuery(sql.ToString());
- }
- /// <summary>
- /// 压缩大文件夹(分块处理)
- /// </summary>
- public static void ZipLargeFolder(string sourceFolder, string zipFilePath, int supplierId, CompressionLevel compressionLevel = CompressionLevel.Optimal)
- {
- // 参数验证
- if (string.IsNullOrEmpty(sourceFolder))
- throw new ArgumentNullException("sourceFolder", "源文件夹路径不能为空");
- if (string.IsNullOrEmpty(zipFilePath))
- throw new ArgumentNullException("zipFilePath", "压缩文件路径不能为空");
- if (!Directory.Exists(sourceFolder))
- {
- throw new DirectoryNotFoundException("源文件夹不存在: " + sourceFolder);
- }
- // 确保目标目录存在
- var zipDir = Path.GetDirectoryName(zipFilePath);
- if (!string.IsNullOrEmpty(zipDir) && !Directory.Exists(zipDir))
- {
- Directory.CreateDirectory(zipDir);
- }
- if (File.Exists(zipFilePath))
- {
- File.Delete(zipFilePath);
- }
- // 使用 EnumerateFiles 减少内存使用
- var files = Directory.EnumerateFiles(sourceFolder, "*.*", SearchOption.AllDirectories);
- using (var fileStream = new FileStream(zipFilePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192))
- using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create, true))
- {
- foreach (var file in files)
- {
- try
- {
- string fileName = Path.GetFileName(file);
- if (supplierId == 14)
- {
- fileName = dealMemoName(fileName);
- }
- // 获取相对路径
- string relativePath = GetRelativePath(sourceFolder, file);
- // 创建zip条目
- var entry = zipArchive.CreateEntry(fileName, compressionLevel);
- // 使用流写入文件内容
- using (var entryStream = entry.Open())
- using (var stream = File.OpenRead(file))
- {
- // 使用更大的缓冲区提高性能
- stream.CopyTo(entryStream, 81920);
- }
- }
- catch (Exception ex)
- {
- // 记录错误但继续处理其他文件
- writeLog("压缩文件失败: 错误: " + ex);
- }
- }
- }
- }
- // 辅助方法:获取相对路径
- private static string GetRelativePath(string basePath, string fullPath)
- {
- Uri baseUri = new Uri(basePath + Path.DirectorySeparatorChar);
- Uri fullUri = new Uri(fullPath);
- Uri relativeUri = baseUri.MakeRelativeUri(fullUri);
- return Uri.UnescapeDataString(relativeUri.ToString()).Replace('\\', '/');
- }
- public static void addLog(string ctid, int userid, string con, int orderState = 0, int aftersaleState = 0)
- {
- CeErpTradeLog log = new CeErpTradeLog();
- log.tid = ctid;
- log.UserId = userid;
- log.Con = con;
- log.OrderState = orderState;
- log.AfterSaleState = aftersaleState;
- log.OperateTime = DateTime.Now;
- log.Create();
- }
- private static string logPath = ConfigurationManager.AppSettings["curPath"] + "\\log";
- private static object logFlag = new object();
- public static void writeLog(string log)
- {
- lock (logFlag)
- {
- using (FileStream fileStream = new FileStream(logPath + "\\" + DateTime.Now.ToString("yy-MM-dd") + ".log", FileMode.Append, FileAccess.Write))
- {
- using (StreamWriter sw = new StreamWriter(fileStream, Encoding.Default))
- {
- sw.Write(log + " ------时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");
- sw.Flush();
- }
- }
- }
- }
- }
|