一、session:html
session記錄到數據庫中,sql數據庫自帶程序C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regsql.exe,能夠在命令行執行web
「C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regsql.exe -S . -E -ssadd -sstype c -d TestSessionStore」會在數據庫中生成一個名爲TestSessionStore的數據庫,這就是爲session而生的,而後在web.config中的sessionState改成sql
<sessionState mode="SQLServer" allowCustomSqlDatabase="true" sqlConnectionString="server=數據庫; database=數據庫名;uid=賬號;pwd=密碼;" cookieless="false" timeout="60"> </sessionState>
這樣,再用sessin就會記錄在數據庫中了。不過若是直接運行.exe程序手動生成數據庫,會報錯,提示無會話狀態。shell
二、task:數據庫
用多線程方法能夠減小發送大量郵件花費時間長的問題(SMTP限制以後再說),task是對ThreadPool線程池的封裝,相對於線程池具備不少優點,好比:(1)ThreadPool不支持線程的取消、完成、失敗通知等交互性操做;(2)ThreadPool不支持線程執行的前後次序;經過對ThreadPool進行封裝,因而.net Framework4.0有了TPL和Task。也就是說,相對於線程池,task使我能對線程的可控性大大提升了。cookie
(1)普通用法:session
Task t = new Task(() => { Console.WriteLine("任務開始"); }); t.Start(); t.ContinueWith((task) => { Console.WriteLine("任務完成"); });
(2)任物工廠:多線程
Task[] tasks = new Task[] { taskFactory.StartNew(() => Add(cts.Token)), taskFactory.StartNew(() => Add(cts.Token)), taskFactory.StartNew(() => Add(cts.Token)) }; //CancellationToken.None指示TasksEnded不能被取消 taskFactory.ContinueWhenAll(tasks, TasksEnded, CancellationToken.None);
CancellationTokenSource是 通知 CancellationToken,告知其應被取消。當其被實例化後,執行.Canale()方法,便可取消線程。app
task能夠等待某個線程執行完成後再執行:less
t1.Wait(); //等待任務t1完成 Task.WaitAll(t2, t3); //等待任務t2和t3完成 t4.ContinueWith(TaskEndedByCatch); //t4執行完成後繼續執行TaskEndedByCatch方法 taskFactory.ContinueWhenAll(tasks, TasksEnded, CancellationToken.None); //工廠內全部線程執行完畢後,執行TasksEnded方法,CancellationToken.None指示此方法不能被取消。
三、解壓:
對於傳入的文件,多是文本文件,也多是壓縮文件,這就要求將傳入的壓縮文件解壓並對文件路徑進行記錄,並且因爲壓縮文件格式不肯定,因此調用WinRAR軟件進行解壓。
1 /// <summary> 2 /// 利用 WinRAR 進行解壓縮 3 /// </summary> 4 /// <param name="path">文件解壓路徑(絕對路徑)</param> 5 /// <param name="rarPath">將要解壓縮文件的存放目錄(絕對路徑)</param> 6 /// <param name="rarName">將要解壓縮文件名(包括後綴)</param> 7 /// <returns>true 或 false。解壓縮成功返回 true,反之,false。</returns> 8 public bool UnRarOrZip(string path, string rarPath, string rarName) 9 { 10 bool flag = false; 11 try 12 { 13 RegistryKey regkey = Registry.ClassesRoot.OpenSubKey(@"WinRAR.ZIP\shell\open\command");//根據註冊表,獲取WinRAR的運行路徑 14 if (regkey != null) 15 { 16 Object regvalue = regkey.GetValue(""); 17 string rarexe = regvalue.ToString(); 18 regkey.Close(); 19 rarexe = rarexe.Substring(1, rarexe.Length - 7); 20 21 Directory.CreateDirectory(path); 22 //解壓縮命令,至關於在要壓縮文件(rarName)上點右鍵->WinRAR->解壓到當前文件夾 23 string cmd = string.Format("x {0} {1} -y", 24 rarName, 25 path); 26 var startinfo = new ProcessStartInfo 27 { 28 FileName = rarexe, 29 Arguments = cmd, 30 WindowStyle = ProcessWindowStyle.Hidden, 31 WorkingDirectory = rarPath 32 }; 33 34 var process = new Process {StartInfo = startinfo}; 35 process.Start(); 36 process.WaitForExit(); 37 if (process.HasExited) 38 { 39 flag = true; 40 } 41 process.Close(); 42 } 43 } 44 catch (Exception e) 45 { 46 throw e; 47 } 48 return flag; 49 } 50 51 public void Dispose() 52 { 53 throw new NotImplementedException(); 54 } 55 }
四、文件操做:
系統中須要對文件和文件夾進行讀寫操做。
建立文件或文件夾:
1 //建立文件夾 2 public void CreateDirectory(string pathName) 3 { 4 if (!Directory.Exists(pathName)) 5 { 6 Directory.CreateDirectory(pathName); 7 } 8 } 9 10 //建立文件 11 public void CreateFile(string pathName) 12 { 13 if (!File.Exists(pathName)) 14 { 15 File.Create(pathName); 16 } 17 }
獲取文件名或文件夾名:
1 //獲取目錄下全部文件名 2 public List<string> GetAllFiles(string path) 3 { 4 var dir = new DirectoryInfo(path); 5 var fiList = new List<FileInfo>(); 6 if (dir.Exists) 7 { 8 fiList.AddRange(dir.GetFiles()); 9 } 10 var fileName = new List<string>(); 11 if (fiList.Count != 0) 12 { 13 fileName.AddRange(fiList.Select(dl => dl.Name)); 14 } 15 return fileName; 16 } 17 18 //獲取目錄下全部文件夾名 19 public List<string> GetAllDirectorys(string path) 20 { 21 var dir = new DirectoryInfo(path); 22 var diList = new List<DirectoryInfo>(); 23 if (dir.Exists) 24 { 25 diList.AddRange(dir.GetDirectories()); 26 } 27 var fileName = new List<string>(); 28 if (diList.Count != 0) 29 { 30 fileName.AddRange(diList.Select(dl => dl.Name)); 31 } 32 return fileName; 33 }
刪除文件:
1 //刪除文件 2 public void DeleteFile(string path) 3 { 4 //判斷文件是否是存在 5 if (!File.Exists(path)) return; 6 //文件刪除 7 File.Delete(path); 8 }
清空文件夾:
1 //清空文件夾 2 public void DeleteDirectory(string path) 3 { 4 //判斷文件是否是存在 5 if (!Directory.Exists(path)) return; 6 //文件夾清空 7 DeleteFolder(path); 8 } 9 public static void DeleteFolder(string dir) 10 { 11 foreach (string d in Directory.GetFileSystemEntries(dir)) 12 { 13 if (File.Exists(d)) 14 { 15 FileInfo fi = new FileInfo(d); 16 if (fi.Attributes.ToString().IndexOf("ReadOnly", System.StringComparison.Ordinal) != -1) 17 fi.Attributes = FileAttributes.Normal; 18 File.Delete(d);//直接刪除其中的文件 19 } 20 else 21 { 22 var d1 = new DirectoryInfo(d); 23 if (d1.GetFiles().Length != 0) 24 { 25 DeleteFolder(d1.FullName);////遞歸刪除子文件夾 26 } 27 Directory.Delete(d); 28 } 29 } 30 }
獲取目錄下第一次出現文件的路徑:
1 public string GetNewUrl(string pathUrl, string pathName) 2 { 3 var files = GetAllFiles(pathUrl); 4 if (files.Count == 0) 5 { 6 var directions = GetAllDirectorys(pathUrl); 7 if (directions.Count > 0) 8 { 9 pathName += "/" + directions.FirstOrDefault(); 10 GetNewUrl(pathUrl + "\\" + directions.FirstOrDefault(), pathName); 11 } 12 } 13 return pathName; 14 }
五、對於excel文件的導入導出操做:
系統數據導入多是txt文件,也多是excel文件。對於導入的Excel文件,使用NPOI進行操做。
excel文件操做類:
1 private HSSFWorkbook _hssfworkbook; 2 3 public void InitializeWorkbook(string path) 4 { 5 using (var file = new FileStream(path, FileMode.Open, FileAccess.Read)) 6 { 7 _hssfworkbook = new HSSFWorkbook(file); 8 } 9 } 10 11 public void InitializeWorkbook(FileUpload uploadfile) 12 { 13 uploadfile.SaveAs(HttpContext.Current.Server.MapPath("~/Content/excel.xls")); 14 string path = HttpContext.Current.Server.MapPath("~/Content/excel.xls"); 15 using (var file = new FileStream(path, FileMode.Open, FileAccess.Read)) 16 { 17 _hssfworkbook = new HSSFWorkbook(file); 18 } 19 } 20 21 /// <summary> 22 /// 數據導出 23 /// </summary> 24 /// <param name="sheetName">Excel Sheet名稱</param> 25 /// <param name="cellNames">列名</param> 26 /// <param name="setCellValue">設置列值的委託方法</param> 27 /// <returns></returns> 28 public MemoryStream ExportEdm(string sheetName, string[] cellNames, Action<ISheet> setCellValue) 29 { 30 using (var output = new MemoryStream()) 31 { 32 IWorkbook workBook = new HSSFWorkbook(); 33 var sheet = workBook.CreateSheet(sheetName); 34 var headRow = sheet.CreateRow(0); 35 for (int i = 0; i < cellNames.Length; i++) 36 headRow.CreateCell(i).SetCellValue(cellNames[i]); 37 setCellValue(sheet); 38 for (int i = 0; i < cellNames.Length; i++) 39 sheet.AutoSizeColumn(i); 40 workBook.Write(output); 41 return output; 42 } 43 }
excel導入導出實例:
1 /// <summary> 2 /// Excel數據導入 3 /// </summary> 4 public void GetExcel(string path) 5 { 6 var uplodeExcel = new ExcelHelper(); 7 uplodeExcel.InitializeWorkbook(path); 8 var list = uplodeExcel.SetCurrentSheet(); 9 } 10 11 /// <summary> 12 /// Excel導出EDM 13 /// </summary> 14 public ActionResult ReportExcel() 15 { 16 var list = (from entity in models 17 let model = _sendService.GetCountList(entity.SendTableName) 18 select new SendTypeStatis 19 {}).ToList(); 20 string[] cellNames = 21 { 22 "EDM名稱", "真實路徑" 23 }; 24 var output = new ReportExcel().ExportEdm("EDM導出", cellNames, r => 25 { 26 if (!list.Any()) return; 27 var rowNumber = 1; 28 foreach (var ml in list) 29 { 30 var number = 0; 31 var row = r.CreateRow(rowNumber++); 32 row.CreateCell(number++).SetCellValue(ml.EdmName); 33 row.CreateCell(number).SetCellValue(ml.EdmNewUrl); 34 } 35 }); 36 string saveAs = string.Format("數據導出-{0:d}.xls", DateTime.Now.Ticks); 37 Response.ContentType = "application/vnd.ms-excel"; 38 Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAs)); 39 Response.BinaryWrite(output.GetBuffer()); 40 Response.End(); 41 42 return Json("success"); 43 }