下载文件,不适用于ASP

下载文件:

100多行代码完毕6秒达成50万条八线程并发日志文件写入,50万日志文件

100多行代码实现6秒落成50万条十二线程并发日志文件写入,帮衬日志文件分隔

日志工具类代码:

美高梅开户网址 1using
System; using System.Collections.Concurrent; using
System.Collections.Generic; using System.IO; using System.Linq; using
System.Text; using System.Threading; using System.Threading.Tasks;
namespace Utils { /// <summary> /// 写日志类 /// </summary>
public class LogUtil { #region 字段 public static object _lock = new
object(); public static string path = “D:\\log”; public static int
fileSize = 10 * 1024 * 1024; //日志分隔文件大小 private static
ConcurrentQueue<Tuple<string, string>> msgQueue = new
ConcurrentQueue<Tuple<string, string>>(); #endregion
#region 静态构造函数 static LogUtil() { Thread thread = new Thread(new
ThreadStart(() => { try { int i; List<string> list;
Tuple<string, string> tuple; while (true) { i = 0; list = new
List<string>(); while (msgQueue.TryDequeue(out tuple) && i++ <
一千0) { list.Add(tuple.Item1.PadLeft(8) + tuple.Item2); } if
(list.Count > 0) { WriteFile(list, CreateLogPath()); }
Thread.Sleep(1); } } catch { } })); thread.IsBackground = true;
thread.Start(); } #endregion #下载文件,不适用于ASP。region 写文件 /// <summary> ///
写文件 /// </summary> public static void
WriteFile(List<string> list, string path) { try { if
(!Directory.Exists(Path.GetDirectoryName(path))) {
Directory.CreateDirectory(Path.GetDirectoryName(path)); } if
(!File.Exists(path)) { using (FileStream fs = new FileStream(path,
FileMode.Create)) { fs.Close(); } } using (FileStream fs = new
FileStream(path, FileMode.Append, FileAccess.Write)) { using
(StreamWriter sw = new StreamWriter(fs)) { list.ForEach(item => {
#region 日志内容 string value = string.Format(@”{0} {1}”,
DateTime.Now.ToString(“yyyy-MM-dd HH:mm:ss.fff”), item); #endregion
sw.WriteLine(value); }); sw.Flush(); } fs.Close(); } } catch { } }
#endregion #region 生成日志文件路径 /// <summary> ///
生成日志文件路径 /// </summary> public static string
CreateLogPath() { int index = 0; string logPath; bool bl = true; do {
index++; logPath = 帕特h.Combine(path, “Log” +
DateTime.Now.ToString(“yyyyMMdd”) + (index == 1 ? “” : “_” +
index.ToString()) + “.txt”); if (File.Exists(logPath)) { FileInfo
fileInfo = new FileInfo(logPath); if (fileInfo.Length < fileSize) {
bl = false; } } else { bl = false; } } while (bl); return logPath; }
#endregion #region 写错误日志 /// <summary> /// 写错误日志 ///
</summary> public static void LogError(string log) {
msgQueue.Enqueue(new Tuple<string, string>(“[Error] “, log)); }
#endregion #region 写操作日志 /// <summary> /// 写操作日志 ///
</summary> public static void Log(string log) {
msgQueue.Enqueue(new Tuple<string, string>(“[Info] “, log)); }
#endregion } } View Code

测试代码:

美高梅开户网址 2using
System; using System.Collections.Generic; using System.ComponentModel;
using System.Data; using System.Drawing; using System.Linq; using
System.Text; using System.Threading; using System.Threading.Tasks; using
System.Windows.Forms; using Utils; namespace WindowsFormsApplication1 {
public partial class Form1 : Form { public Form1() {
InitializeComponent(); } private void Form1_Load(object sender,
EventArgs e) { LogUtil.path = Application.StartupPath + “\\log”;
//初步化日志路径 } private void button1_Click(object sender, EventArgs
e) { for (int n = 0; n < 10; n++) { Thread thread = new Thread(new
ThreadStart(() => { int i = 0; for (int k = 0; k < 50000; k++) {
LogUtil.Log((i++).ToString() + ”
abcdab[email protected]#$%^&dabcdabcdabcdabcdabcdabcdabcdabcd”);
} })); thread.IsBackground = true; thread.Start(); } } } } View Code

 测试截图:

美高梅开户网址 3

美高梅开户网址 4

 

100多行代码完结6秒达成50万条八线程并发日志文件写入,帮助日志文…

C#写文本日志扶助类(协助二十多线程)创新版(不适用于ASP.NET程序),

由于iis的自动回收机制,不适用于ASP.NET程序

代码:

美高梅开户网址 5using
System; using System.Collections.Concurrent; using System.Configuration;
using System.IO; using System.Text; using System.Threading; using
System.Threading.Tasks; namespace CommonDll { /// <summary> ///
写日志类 /// </summary> public class LogUtil { #region 字段
public static string path =
ConfigurationManager.AppSettings[“LogPath”]; public static int
fileSize = 10 * 1024 * 1024; //日志分隔文件大小 private static
ConcurrentQueue<Tuple<string, DateTime>> queue = new
ConcurrentQueue<Tuple<string, DateTime>>(); #endregion
#region 构造函数 static LogUtil() { Task.Factory.StartNew(new
Action(delegate() { StringBuilder log; string path; Tuple<string,
DateTime> tuple; string item; while (true) { log = new
StringBuilder(); path = CreateLogPath(); while (queue.TryDequeue(out
tuple)) { item = string.Format(@”{0} {1}”,
tuple.Item2.ToString(“yyyy-MM-dd HH:mm:ss.fff”), tuple.Item1);
log.AppendFormat(“\r\n{0}”, item); } if (log.Length > 0)
WriteFile(log.ToString(2, log.Length – 2), path); Thread.Sleep(100); }
})); } #endregion #region 写文件 /// <summary> /// 写文件 ///
</summary> public static void WriteFile(string log, string path) {
try { if (!Directory.Exists(Path.GetDirectoryName(path))) {
Directory.CreateDirectory(Path.GetDirectoryName(path)); } if
(!File.Exists(path)) { using (FileStream fs = new FileStream(path,
FileMode.Create)) { fs.Close(); } } using (FileStream fs = new
FileStream(path, FileMode.Append, FileAccess.Write)) { using
(StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine(log);
sw.Flush(); } fs.Close(); } } catch { } } #endregion #region
生成日志文件路径 /// <summary> /// 生成日志文件路径 ///
</summary> public static string CreateLogPath() { int index = 0;
string log帕特h; bool bl = true; do { index++; logPath =
Path.Combine(path, “Log” + DateTime.Now.ToString(“yyyyMMdd”) + (index ==
1 ? “” : “_” + index.ToString()) + “.txt”); if (File.Exists(logPath)) {
FileInfo fileInfo = new FileInfo(logPath); if (fileInfo.Length <
fileSize) { bl = false; } } else { bl = false; } } while (bl); return
logPath; } #endregion #region 写错误日志 /// <summary> ///
写错误日志 /// </summary> public static void LogError(string log)
{ queue.Enqueue(new Tuple<string, DateTime>(“[Error] ” + log,
DateTime.Now)); } #endregion #region 写操作日志 /// <summary>
/// 写操作日志 /// </summary> public static void Log(string log) {
queue.Enqueue(new Tuple<string, DateTime>(“[Info] ” + log,
DateTime.Now)); } #endregion } } View Code

测试代码:

美高梅开户网址 6private
void button1_Click(object sender, 伊芙ntArgs e) { int n = 一千0;
DateTime dtStart = DateTime.Now; for (int i = 1; i <= n; i++) {
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object obj) { int
j = (int)obj; LogUtil.Log(“测试” + j.ToString(“00000”)); if (j == n) {
double sec = DateTime.Now.Subtract(dtStart).TotalSeconds;
MessageBox.Show(n + “条日志实现,耗时” + sec.ToString(“0.000”) + “秒”);
} }), i); } } View Code

效果图:

美高梅开户网址 7

 

由于iis的机动回收机制,不适用于ASP.NET程序 代码: using System; using
System.C…

protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add;
dt.Columns.Add;
dt.Columns.Add;
dt.Columns.Add;
dt.Columns.Add;
for (int i = 0; i < 6; i++)
{
dt.Rows.Add();
dt.Rows[i][0] = “CN”+i.ToString();
dt.Rows[i][1] = “EN”+i.ToString();
dt.Rows[i][2] = “JN”+i.ToString();
dt.Rows[i][3] = “HK”+i.ToString();
dt.Rows[i][4] = “TW”+i.ToString();
}

代码:

ExportDataGridToCSV;

后端代码:

}

public IActionResult DownloadFile()
{
var FilePath = @”./files/deparment.xlsx”;
var stream = System.IO.File.OpenRead(FilePath);
return File(stream, “application/vnd.android.package-archive”,
Path.GetFileName(FilePath));
}

/// <summary>
/// Export the data from datatable to CSV file
/// </summary>
/// <param name=”grid”></param>
public void ExportDataGridToCSV(DataTable dt)
{
string strFile = “”;
string path = “”;

页面代码:

//File info initialization
strFile = “test”;
strFile = strFile + DateTime.Now.ToString(“yyyyMMddhhmmss”);
strFile = strFile + “.csv”;
path = Server.MapPath;

<a href=”;

System.IO.FileStream fs = new FileStream(path,
System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, new
System.Text.UnicodeEncoding;
//Tabel header
for (int i = 0; i < dt.Columns.Count; i++)
{
sw.Write(dt.Columns[i].ColumnName);
sw.Write;
}
sw.WriteLine;
//Table body
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
sw.Write(DelQuota(dt.Rows[i][j].ToString;
sw.Write;
}
sw.WriteLine;
}
sw.Flush();
sw.Close();

上传文件:

DownLoadFile;
}

nuget下载:EPPlus.Core

private bool DownLoadFile(string _FileName)
{
try
{
System.IO.FileStream fs = System.IO.File.OpenRead(_FileName);
byte[] FileData = new byte[fs.Length];
fs.Read(FileData, 0, fs.Length);
Response.Clear();
Response.AddHeader(“Content-Type”, “application/notepad”);
string FileName =
System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(_FileName));
Response.AddHeader(“Content-Disposition”, “inline;filename=” +
System.Convert.ToChar + FileName + System.Convert.ToChar;
Response.AddHeader(“Content-Length”, fs.Length.ToString;
Response.BinaryWrite;
fs.Close();
System.IO.File.Delete(_FileName);
Response.Flush();
Response.End();
return true;
}
catch (Exception ex)
{
ex.Message.ToString();
return false;
}
}

基本思路:如今是透过将页面上盛传的公文物保护留至项目地址里面,再读取出来,再判断传入ecxel文件的底部是或不是符合供给,符合则写入数据库

/// <summary>
/// Delete special symbol
/// </summary>
/// <param name=”str”></param>
/// <returns></returns>
public string DelQuota(string str)
{
string result = str;
string[] strQuota ={ “~”, “!”, “@”, “#”, “$”, “%”, “^”, “&”, “*”,
“”, “`”, “;”, “‘”, “,”, “.”, “/”, “:”, “/,”, “<“, “>”, “?” };
for (int i = 0; i < strQuota.Length; i++)
{
if (result.IndexOf(strQuota[i]) > -1)
result = result.Replace(strQuota[i], “”);
}
return result;
}

 美高梅开户网址 8

代码:

后端代码:

public object AddMulitDeparment(IFormCollection files)
美高梅开户网址 ,{
string[] colName = new string[] { “集团名称”, “部门组长”,
“部门名称”, “职员和工人数量”, “部门代码” };
var result = new object();
string message = “”;
if (files != null && files.Files.Count > 0)
{
for (int i = 0; i < files.Files.Count; i++)
{
var file = files.Files[i];
try
{
object path = _importExcelUtil.SaveExcel(file);
FileInfo fileInfo = new FileInfo((string)path);
using (FileStream fs = new FileStream(fileInfo.ToString(),
FileMode.Create))
{
file.CopyTo(fs);
fs.Flush();
}
using (ExcelPackage package = new ExcelPackage(fileInfo))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
if (_importExcelUtil.JudgeCol(worksheet,colName))
{
result = new
{
data = _importExcelUtil.SaveDepToDB(worksheet)
};
System.IO.File.Delete((string)path);
}
}
}
catch (Exception ex)
{
message= ex.Message;
}
}
}
return result;
}

//判断尾部(取出表格内容同)

public bool JudgeCol(ExcelWorksheet worksheet,string[] colName)
{
int ColCount = worksheet.Dimension.Columns;
bool bHeaderRow = true;
//excel下标从1开始
for (int col = 1,index=0; col <= ColCount&&index<colName.Length;
col++,index++)
{
string c = worksheet.Cells[1, col].Value.ToString();
if (!c.Equals(colName[index]))
{
bHeaderRow = false;
throw new
Exception(“格式错误,导入文本的第”+index+”列应为”+colName[index]+”!”);
}
}
return bHeaderRow;
}

前端代码,由于须要上传文件,需求将http请求底部的Content-Type修改为multipart/form-data

*仅作为个人学习记录

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图