/// <summary> /// 获取本机公网地址 /// </summary> /// <returns></returns> public static string GetNetIP() { //初始化返回值 string result = string.Empty; //创建一个Web请求 WebRequest request = WebRequest.Create("http://pv.sohu.com/cityjson?ie=utf-8"); //定义一个流读取器 StreamReader reader = null; try { //读取Web请求的返回值 reader = new StreamReader(request.GetResponse().GetResponseStream()); //得到读取出来的网页内容 string htmlContent = reader.ReadToEnd(); //利用正则得到IP地址 result = RegularUtil.GetIPv4(htmlContent); } catch (Exception ex) { //如果发生异常就输出到日志 LogUtil.WriteLog(ex); } finally { //最后不管怎样只要流读取器不为空就关闭流读取器,释放资源 if (reader != null) { reader.Close(); reader.Dispose(); } } return(result); }
/// <summary> /// 获取本机公网IP /// </summary> /// <returns></returns> private static string GetNetIP() { string result = string.Empty; HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://www.net.cn/static/customercare/yourip.asp"); using (StreamReader reader = new StreamReader(webRequest.GetResponse().GetResponseStream())) { string htmlContent = reader.ReadToEnd(); result = RegularUtil.Get(htmlContent, RegularUtil.IPADDRESS); } return(result); }
/// <summary> /// 添加收信人 /// </summary> /// <param name="mailMessage">要添加收信人的<see cref="MailMessage"/>对象</param> /// <param name="receiveAddress">收信人地址</param> public static void AddReceiver(MailMessage mailMessage, params string[] receiveAddress) { if (mailMessage == null) { throw new NullReferenceException("MailMessage未初始化!"); } foreach (string address in receiveAddress) { if (string.IsNullOrEmpty(address)) { continue; } if (!RegularUtil.VerifyEmail(address)) { throw new ArgumentException("收信人地址错误!", nameof(receiveAddress)); } mailMessage.To.Add(address); } }
/// <summary> /// 创建一个<see cref="MailMessage"/>对象 /// </summary> /// <param name="senderAddress">发信人地址</param> /// <param name="title">邮件标题</param> /// <returns></returns> public static MailMessage CreateMailMessage(string senderAddress, string title = "") { if (StringUtil.IsNullOrEmpty(senderAddress)) { throw new ArgumentNullException(nameof(senderAddress), "发信人地址不允许为空!"); } if (!RegularUtil.VerifyEmail(senderAddress)) { throw new ArgumentException("发件人地址错误!", nameof(senderAddress)); } MailMessage result = new MailMessage(); result.From = new MailAddress(senderAddress); result.Subject = title; result.IsBodyHtml = true; result.BodyEncoding = Encoding.Default; result.Priority = MailPriority.Normal; return(result); }
public async Task <IActionResult> UploadQuestionFile([FromForm] FileUpload fileUpload, [FromServices] IWebHostEnvironment enviroment) { if (ModelState.IsValid) { var filePath = Path.Combine(enviroment.WebRootPath, "Upload", loginUser.UserName, DateTime.Now.ToString("yyyyMMdd")); if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } var fileName = string.Format("{0}{1}", Guid.NewGuid(), Path.GetExtension(fileUpload.UploadFile.FileName)); fileName = Path.Combine(filePath, fileName); using (FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write)) { fileUpload.UploadFile.CopyTo(fs); } IEnumerable <DataSet> excelData = ReadQuestionFromExcel.ReadExcelFile(fileName); //解析Excel数据 foreach (DataSet ds in excelData) { DataTable excelTable = ds.Tables[0]; if (excelTable == null || excelTable.Rows.Count < 2) { continue; } DataRow titleRow = excelTable.Rows[0]; //拿到标题行 int columnNum = excelTable.Columns.Count; //得到列数 int questionColumnIndex = 0, answerColumnIndex = 0; List <int> solutionColumnIndexs = new List <int>(); //得到题目列,答案列,正确答案列的索引 for (int i = 0; i < columnNum; i++) { string rowValue = RowUtil.GetString(titleRow, excelTable.Columns[i].ColumnName); if (rowValue.Equals("题目")) { questionColumnIndex = i; } if (rowValue.StartsWith("选项")) { if (!solutionColumnIndexs.Contains(i)) { solutionColumnIndexs.Add(i); } } if (rowValue.Equals("答案")) { answerColumnIndex = i; } } DataColumn questionColumn = excelTable.Columns[questionColumnIndex]; DataColumn answerColumn = excelTable.Columns[answerColumnIndex]; DataColumn[] solutionColumns = new DataColumn[solutionColumnIndexs.Count]; //移除标题行 excelTable.Rows.Remove(titleRow); for (int i = 0; i < solutionColumnIndexs.Count; i++) { solutionColumns[i] = excelTable.Columns[solutionColumnIndexs[i]]; } //生成问题和答案 for (int i = 0; i < excelTable.Rows.Count; i++) { DataRow currentRow = excelTable.Rows[i]; //得到题目 string questionName = RowUtil.GetString(currentRow, questionColumn.ColumnName); if (string.IsNullOrEmpty(questionName)) { continue; } //得到正确答案序号 string answer = RowUtil.GetString(currentRow, answerColumn.ColumnName); List <string> solutions = new List <string>(); //得到所有答案 foreach (DataColumn column in solutionColumns) { string solution = RowUtil.GetString(currentRow, column.ColumnName); solutions.Add(solution); } CreateQuestionInfo questionInfo = new CreateQuestionInfo(); questionInfo.Name = questionName; questionInfo.QuestionType = QuestionType.Radio; questionInfo.QuestionTypeInt = (int)questionInfo.QuestionType; questionInfo.QuestionScore = 1; questionInfo.QuestionGroupName = fileUpload.UploadFile.FileName.Replace(Path.GetExtension(fileUpload.UploadFile.FileName), null); questionInfo.SolutionNames = solutions.AsEnumerable(); List <double> solutionScore = new List <double>(); string regexStr = @"^[A-Za-z]+"; //计算选项得分 foreach (string item in questionInfo.SolutionNames) { //如果正确答案是A~Z,就判断所有选项的开头,否则判断答案是否包含 if (RegularUtil.Regex(regexStr, answer)) { if (item.StartsWith(answer)) //选项的开头和答案一致,证明是正确答案 { solutionScore.Add(1); } else { solutionScore.Add(0); } } else { if (item.Contains(answer)) //选项包含答案,就认为是正确答案 { solutionScore.Add(1); } else { solutionScore.Add(0); } } } questionInfo.SolutionScore = solutionScore.AsEnumerable(); //去掉选项前边的序号 List <string> solutons1 = new List <string>(); foreach (string solution in solutions) { int index = solution.IndexOf('.'); string solutionValue = solution.Substring(index + 1, solution.Length - index - 1); solutons1.Add(solutionValue); } questionInfo.SolutionNames = solutons1.AsEnumerable(); CreateQuestion(questionInfo); } } return(RedirectToAction(nameof(Index))); } ModelState.AddModelError("UploadFile", "目前只支持Excel文件(.xls/.xlsx)哦"); return(View(fileUpload)); }
/// <summary> /// 发送邮件 /// </summary> /// <param name="receivers">收件人邮箱列表</param> /// <param name="senderAddress">发件人邮箱</param> /// <param name="senderPasscode">发件人密码</param> /// <param name="emailBody">邮件内容</param> /// <param name="emailTitle">邮件标题</param> /// <param name="enableSsl">是否启用SSL</param> /// <param name="emailAttachments">邮件附件</param> public static void SendEmail(List <string> receivers, string senderAddress, string senderPasscode, string emailBody, string emailTitle, bool enableSsl, params FileInfo[] emailAttachments) { if (string.IsNullOrEmpty(senderAddress) || !RegularUtil.RegexEmail(senderAddress)) { throw new ArgumentException("请填写有效的发件人邮箱", "senderAddress"); } //定义一个邮件对象 MailMessage mailMessage = new MailMessage(); //循环收件人列表添加收件人 foreach (string receiveAddress in receivers) { if (string.IsNullOrEmpty(receiveAddress) || !RegularUtil.RegexEmail(receiveAddress)) { continue; } mailMessage.To.Add(receiveAddress); } if (mailMessage.To.Count <= 0) { throw new ArgumentException("请填写收件人"); } //添加发件人 mailMessage.From = new MailAddress(senderAddress, DeviceUtil.GetSystemUserName()); //设置邮件标题 mailMessage.Subject = emailTitle; //设置邮件内容 mailMessage.Body = emailBody; //默认使用HTML格式的邮件内容 mailMessage.IsBodyHtml = true; //邮件内容编码使用默认编码 mailMessage.BodyEncoding = Encoding.Default; //设置邮件优先级为普通,似乎是过高容易被当成垃圾邮件 mailMessage.Priority = MailPriority.Normal; //如果附件列表不为空且包含附件 if (emailAttachments != null && emailAttachments.Length > 0) { //循环附件列表添加附件 foreach (FileInfo attachmentFile in emailAttachments) { //定义一个附件对象并设置附件路径,附件的创建,修改,访问时间 Attachment attachment = new Attachment(attachmentFile.FullName); ContentDisposition contentDisposition = attachment.ContentDisposition; contentDisposition.CreationDate = attachmentFile.CreationTime; contentDisposition.ModificationDate = attachmentFile.LastWriteTime; contentDisposition.ReadDate = attachmentFile.LastAccessTime; mailMessage.Attachments.Add(attachment); } } //定义一个Smtp客户端对象 SmtpClient smtpClient = new SmtpClient(); //获取第一个收件人的地址 string firstReciever = receivers.Where(p => p.IndexOf('@') > -1).FirstOrDefault(); //计算收件人的Smtp协议 int hostStart = firstReciever.IndexOf('@'); string smtpHost = string.Format("smtp{0}", firstReciever.Substring(hostStart, firstReciever.Length - hostStart).Replace('@', '.')); //设置smtp协议 smtpClient.Host = smtpHost; //设置是否启用SSL smtpClient.EnableSsl = enableSsl; //设置Smtp客户端使用默认的身份验证方式 smtpClient.UseDefaultCredentials = true; //设置Smtp客户端的用户密码,用于发送邮件 smtpClient.Credentials = new NetworkCredential(mailMessage.From.Address, senderPasscode); //设置客户端发送邮件的方式为网络的方式 smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; try { //开始发送邮件 smtpClient.SendMailAsync(mailMessage).Wait(); } catch (Exception ex) { LogUtil.WriteLog(ex); //如果错误提示为需要开启SSL并且没有打开SSL if (ex.Message == "need EHLO and AUTH first" && !enableSsl) { //迭代发送邮件并启用SSL SendEmail(receivers, senderAddress, senderPasscode, emailBody, emailTitle, true, emailAttachments); } else { //否则有可能发件失败了,抛出异常 throw ex; } } }