private int OnReadData(byte[] buf, int size, int nmemb, object extraData) { long SPosition = 0; try { // UploadStream.Seek(UpLoadedSize, SeekOrigin.Current); UpLoadedSize += buf.Length; return(UploadStream.Read(buf, 0, size * nmemb)); /* * byte[] data = (byte[])extraData; * * using (MemoryStream FStream = new MemoryStream(data)) * { * if (BrokenOpen) //支持断点续传 * { * SPosition = upLoadedSize; //已经上传的字节数 * } * FStream.Seek(SPosition, SeekOrigin.Current); * return FStream.Read(buf, 0, size * nmemb); * } */ } catch (Exception ex) { LogLocal.log().SaveLog(new LogEntity(string.Format("OnReadData:上传起始字节:{0},发生错误:{1}", SPosition, ex.Message), LogType.Plat, LogLevel.ERROR)); throw ex; } }
private int OnWriteData(byte[] buf, int size, int nmemb, object extraData) { try { DownFileStream.Write(buf, 0, buf.Length); /* * using (FileStream FStream = new FileStream(downFileName, FileMode.OpenOrCreate)) * { * // { * SPosition = FStream.Length; //获取已经下载的长度 * // } * FStream.Seek(SPosition, SeekOrigin.Current); * DownedLen += buf.Length; * if (SPosition <= DownedLen) * { * FStream.Write(buf, 0, buf.Length); * } * }*/ } catch (Exception ex) { LogLocal.log().SaveLog(new LogEntity(string.Format("OnReadData发生错误:{1}", ex.Message), LogType.Plat, LogLevel.ERROR)); throw ex; } return(size * nmemb); }
/// <summary> /// 获取本地在用的IP地址 /// </summary> /// <returns></returns> public static string getLocalUsingIP() { try { var ni = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface item in ni) { if (item.OperationalStatus == OperationalStatus.Up) //&& item.NetworkInterfaceType == ? { foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == AddressFamily.InterNetwork & !IPAddress.IsLoopback(ip.Address)) { return(ip.Address.ToString()); } } } } throw new Exception("No network adapters with an IPv4 address in the system!"); } catch (Exception e) { LogLocal.log().SaveLog(new LogEntity("获取当前IP失败:" + e.Message, LogType.Plat, LogLevel.ERROR)); return(""); } }
/// <summary> /// 获取当前目录下明细(包含文件和文件夹) /// </summary> /// <param name="folder"></param> /// <returns></returns> public List<string> GetFilesDetailList(string folder) { try { init(folder); List<string> list = new List<string>(); ftpReq.Method = WebRequestMethods.Ftp.ListDirectoryDetails; using (FtpWebResponse res = (FtpWebResponse)ftpReq.GetResponse()) { using (StreamReader sr = new StreamReader(res.GetResponseStream())) { string s; while ((s = sr.ReadLine()) != null) { list.Add(s); } } } return list; } catch (Exception ex) { string info = "获取文件夹列表明细失败:" + ex.Message; LogLocal.log().SaveLog(new LogEntity(info, LogType.Plat, LogLevel.ERROR)); throw new Exception(info); } }
private int onProgress(object extraData, double dlTotal, double dlNow, double ulTotal, double ulNow) { try { double speed = 0; TimeSpan ts = DateTime.Now.Subtract(BeginTime); if ((DownOrUp == 1) && (state == 0)) //下载 { if (ts.Seconds > 0) { speed = dlNow / ts.Seconds; } Speed = speed; TotalSize = Convert.ToInt64(dlTotal + StartDownPosion); CompleteSize = Convert.ToInt64(dlNow + StartDownPosion); if ((dlNow + dlTotal) > 0) { onUpProgress(Owner, TotalSize, CompleteSize, speed); } } else if ((DownOrUp == 2) && (state == 0)) //上传 { if (ts.Seconds > 0) { speed = ulNow / ts.Seconds; } Speed = speed; TotalSize = UploadStream.Length; // Convert.ToInt64(ulTotal); CompleteSize = Convert.ToInt64(ulNow); if ((ulNow + ulTotal) > 0) { onUpProgress(Owner, TotalSize, CompleteSize, speed); } } if (state == 2) //停止 { if (DownOrUp == 1) { easy.Reset(); } if (DownOrUp == 2) { easy.Pause(); } } System.Windows.Forms.Application.DoEvents(); } catch (Exception ex) { LogLocal.log().SaveLog(new LogEntity(string.Format("CURL-onProgress:总大小:{0},已完成传输大小:{1},发生错误:{2}", TotalSize, CompleteSize, ex.Message), LogType.Plat, LogLevel.ERROR)); throw ex; } return(0); }
public static string getFileExtByHeader(string filePath, int byteCount) { byte[] hed = getFileHeader(filePath, byteCount); string head = getFileExtByHeader(StringUtil.byteToHexStr(hed)); if (head.Equals("")) { LogLocal.log().SaveLog(new LogEntity(string.Format("获取文件【{0}】的文件头信息为空!", filePath), LogType.Plat, LogLevel.DEBUG)); } return(getFileExtByHeader(StringUtil.byteToHexStr(hed))); }
public override void RollbackTransaction() { try { db.RollbackTransaction(); } catch (Exception ex) { LogLocal.log().SaveLog(new LogEntity(ex.Message, LogType.Plat, LogLevel.ERROR)); LastErrorMessage = ex.Message; } }
public override bool getFile(string table, string field, string IDValue, string filePath) { try { LogLocal.log().SaveLog(new LogEntity(string.Format("在表:{0}中ID为:{1}的{2}字段中读取文件", table, field, IDValue), LogType.Plat, LogLevel.DEBUG)); return(db.getFile(table, field, IDValue, filePath)); } catch (Exception ex) { LogLocal.log().SaveLog(new LogEntity(ex.Message, LogType.Plat, LogLevel.ERROR)); LastErrorMessage = ex.Message; return(false); } }
/// <summary> /// 在FTP上创建目录 /// </summary> /// <param name="dirName"></param> public void MakeDir(string dirName) { try { init(dirName); ftpReq.Method = WebRequestMethods.Ftp.MakeDirectory; using (FtpWebResponse response = (FtpWebResponse)ftpReq.GetResponse()) { } } catch (Exception ex) { string info = "创建目录失败:" + ex.Message; LogLocal.log().SaveLog(new LogEntity(info, LogType.Plat, LogLevel.ERROR)); throw new Exception(info); } }
public static string Parms2Collection(string parm, out System.Collections.Specialized.NameValueCollection parmCollection) { try { string u = ""; parmCollection = ParseUrl(parm, out u); LogLocal.log().SaveLog(new LogEntity(u, LogType.Plat, LogLevel.DEBUG)); return(""); } catch (Exception ex) { parmCollection = null; return(ex.Message); } }
//增加后缀配置(suffix),支持同一系统多个数据库连接 public static DataService dataService(string suffix = "") { if (cfg == null) { try { cfg = new DataCfg(suffix); } catch (Exception ex) { LogLocal.log().SaveLog(new LogEntity(ex.Message, LogType.Plat, LogLevel.DEBUG)); } } return(dbService); }
/// <summary> /// 删除FTP文件 /// </summary> /// <param name="remoteFile"></param> /// <returns></returns> public bool DeletFile(string remoteFile) { try { init(remoteFile); ftpReq.Method = WebRequestMethods.Ftp.DeleteFile; using (FtpWebResponse response = (FtpWebResponse)ftpReq.GetResponse()) { } return true; } catch (Exception ex) { string info = "删除文件失败:" + ex.Message; LogLocal.log().SaveLog(new LogEntity(info, LogType.Plat, LogLevel.ERROR)); throw new Exception(info); } }
public override bool setFile(string table, string field, string IDValue, string filePath) { try { Application.DoEvents(); if (conn == null) { throw new Exception(DBNOTINIT); } FileInfo fi = new FileInfo(filePath); FileStream fs = fi.OpenRead(); byte[] bytes = new byte[fs.Length]; fs.Read(bytes, 0, Convert.ToInt32(fs.Length)); if (conn.State == ConnectionState.Closed) { conn.Open(); } SQLiteCommand cmd = new SQLiteCommand(); cmd.Connection = (SQLiteConnection)conn; if ((inTranscation) && (transaction != null)) { cmd.Transaction = (SQLiteTransaction)transaction; } cmd.CommandType = CommandType.Text; cmd.CommandText = string.Format("UPDATE {0} SET {1} = :file WHERE ID='{2}'", table, field, IDValue); LogLocal.log().SaveLog(new LogEntity(cmd.CommandText, LogType.Plat, LogLevel.DEBUG)); cmd.Parameters.Add("file", DbType.Binary).Value = bytes; int n = cmd.ExecuteNonQuery(); cmd.Dispose(); return(true); } catch (Exception ex) { Console.WriteLine(ex.Message); return(false); } finally { if (!inTranscation) { conn.Close(); } } }
public override bool ExecSql(string sql, bool throwException = false) { try { LogLocal.log().SaveLog(new LogEntity(sql, LogType.Plat, LogLevel.DEBUG)); return(db.ExecSql(sql)); } catch (Exception ex) { LastErrorMessage = ex.Message; LogLocal.log().SaveLog(new LogEntity(ex.Message, LogType.Plat, LogLevel.ERROR)); if (throwException) { throw new Exception(LastErrorMessage); } return(false); } }
/// <summary> /// Http下载文件 /// </summary> /// <param name="aURL">url文件地址</param> /// <param name="outFile">下载文件地址</param> /// <param name="updateProgress">下载进度过程</param> public bool DownloadFile(string aURL, string outFile, OnUpdateProgress updateProgress = null) { try { DownOrUp = 1; //下载标识 if ((!BrokenOpen) && (File.Exists(outFile))) { File.Delete(outFile); } downFileName = outFile; DownFileStream = new FileStream(outFile, FileMode.OpenOrCreate); StartDownPosion = DownFileStream.Length; DownFileStream.Seek(DownFileStream.Length, SeekOrigin.Current); onUpProgress = updateProgress; BeginTime = DateTime.Now; initCurl(aURL); easy.WriteFunction = OnWriteData; easy.ResumeFrom = DownFileStream.Length; easy.Perform(); if (easy.ResponseCode == 200) { return(true); } else { throw new Exception(string.Format("HTTP返回:{0}", easy.ResponseCode)); } } catch (Exception ex) { LogLocal.log().SaveLog(new LogEntity("文件下载失败:" + ex.Message, LogType.Plat, LogLevel.ERROR)); throw ex; } finally { easy = null; DownFileStream.Flush(); DownFileStream.Close(); DownFileStream.Dispose(); DownOrUp = 0; } }
/// <summary> /// 获取硬盘序列号 /// </summary> /// <returns></returns> private static string GetHdId() { try { var lpm = new ManagementClass("Win32_PhysicalMedia").GetInstances(); var serial = ""; foreach (ManagementObject hd in lpm) { var val = hd.Properties["SerialNumber"].Value; serial += val == null ? "" : val.ToString().Trim(); } return(serial); } catch (Exception e) { LogLocal.log().SaveLog(new LogEntity("获取硬盘序列号失败:" + e.Message, LogType.Plat, LogLevel.ERROR)); return(""); } }
/// <summary> /// 获取主板序列号 /// </summary> /// <returns></returns> private static string GetMbId() { try { var myMb = new ManagementClass("Win32_BaseBoard").GetInstances(); var serial = ""; foreach (ManagementObject mb in myMb) { var val = mb.Properties["SerialNumber"].Value; serial += val == null ? "" : val.ToString(); } return(serial); } catch (Exception e) { LogLocal.log().SaveLog(new LogEntity("获取主板序列号失败:" + e.Message, LogType.Plat, LogLevel.ERROR)); return(""); } }
/// <summary> /// ftp上文件改名 /// </summary> /// <param name="oldFilename"></param> /// <param name="newFilename"></param> public void Rename(string oldFilename, string newFilename) { try { init(oldFilename); ftpReq.Method = WebRequestMethods.Ftp.Rename; ftpReq.RenameTo = newFilename; using(FtpWebResponse response = (FtpWebResponse)ftpReq.GetResponse()) { } } catch (Exception ex) { string info = "修改文件名失败:" + ex.Message; LogLocal.log().SaveLog(new LogEntity(info, LogType.Plat, LogLevel.ERROR)); throw new Exception(info); } }
/// <summary> /// 获取BIOS编号 /// </summary> /// <returns></returns> private static string GetBIOSCode() { try { ManagementClass mc = new ManagementClass("Win32_BIOS"); ManagementObjectCollection moc = mc.GetInstances(); string strID = null; foreach (ManagementObject mo in moc) { strID = mo.Properties["SerialNumber"].Value.ToString(); break; } return(strID); } catch (Exception e) { LogLocal.log().SaveLog(new LogEntity("获取硬盘序列号失败:" + e.Message, LogType.Plat, LogLevel.ERROR)); return(""); } }
/// <summary> /// HTTP上传文件 /// </summary> /// <param name="aURL">上传URL地址</param> /// <param name="upFile">待上传文件</param> /// <param name="uploadedSize">已上传文件大小(字节)</param> /// <param name="updateProgress">下载进度过程</param> public bool UploadFile(string aURL, string upFile, long uploadedSize = 0, OnUpdateProgress updateProgress = null) { try { DownOrUp = 2; //上传标识 initCurl(aURL); UpLoadedSize = uploadedSize; easy.ReadFunction = OnReadData; byte[] UploadData = File.ReadAllBytes(upFile); UploadStream = new MemoryStream(UploadData); UploadStream.Seek(UpLoadedSize, SeekOrigin.Current); easy.ReadData = UploadData; onUpProgress = updateProgress; BeginTime = DateTime.Now; easy.Upload = true; easy.InfileSize = UploadData.Length; easy.Post = true; easy.Perform(); if (easy.ResponseCode == 200) { return(true); } else { throw new Exception(string.Format("HTTP返回:{0}", easy.ResponseCode)); } } catch (Exception ex) { LogLocal.log().SaveLog(new LogEntity(string.Format("文件上传URL:\"{0}\" 上传失败:{1}", aURL, ex.Message), LogType.Plat, LogLevel.ERROR)); throw ex; } finally { easy = null; UploadStream.Flush(); UploadStream.Close(); UploadStream.Dispose(); DownOrUp = 0; } }
//取CPU编号 public static string GetCpuID() { try { ManagementClass mc = new ManagementClass("Win32_Processor"); ManagementObjectCollection moc = mc.GetInstances(); String strCpuID = null; foreach (ManagementObject mo in moc) { strCpuID = mo.Properties["ProcessorId"].Value.ToString(); break; } return(strCpuID); } catch (Exception e) { LogLocal.log().SaveLog(new LogEntity("获取CPU ID失败:" + e.Message, LogType.Plat, LogLevel.ERROR)); return(""); } }
public override bool getFile(string table, string field, string IDValue, string filePath) { FileStream pFileStream = null; try { Application.DoEvents(); if (conn == null) { throw new Exception(DBNOTINIT); } if (conn.State == ConnectionState.Closed) { conn.Open(); } string sql = string.Format("SELECT {0} FROM {1} WHERE ID='{2}'", field, table, IDValue); LogLocal.log().SaveLog(new LogEntity(sql, LogType.Plat, LogLevel.DEBUG)); SqlCommand cmd = new SqlCommand(sql, (SqlConnection)conn); if ((inTranscation) && (transaction != null)) { cmd.Transaction = (SqlTransaction)transaction; } SqlDataReader dr = cmd.ExecuteReader(); dr.Read(); byte[] bytes = (byte[])dr[0]; pFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); pFileStream.Write(bytes, 0, bytes.Length); return(true); } finally { if (pFileStream != null) { pFileStream.Close(); } } }
public override DataTable RunSql(string sql, bool throwException = false) { try { LogLocal.log().SaveLog(new LogEntity(sql, LogType.Plat, LogLevel.DEBUG)); DataTable dt = db.RunSql(sql); if (dt == null) { throw new Exception(db.DATASETNULL); } return(dt); } catch (Exception ex) { LastErrorMessage = ex.Message; LogLocal.log().SaveLog(new LogEntity(ex.Message, LogType.Plat, LogLevel.ERROR)); if (throwException) { throw new Exception(LastErrorMessage); } return(null); } }
/// <summary> /// 获取当前目录下文件列表(仅文件) /// </summary> /// <param name="folder"></param> /// <returns></returns> public List<string> GetFileList(string folder) { try { List<string> detail = GetFilesDetailList(folder); List<string> drectory = new List<string>(); foreach (string str in detail) { if (str.Trim().Substring(0, 1).ToUpper() != "D") { string[] tmp = str.Split(' '); string strx = tmp[tmp.Length - 1]; drectory.Add(strx); } } return drectory; } catch (Exception ex) { string info = "获取文件列表失败:" + ex.Message; LogLocal.log().SaveLog(new LogEntity(info, LogType.Plat, LogLevel.ERROR)); throw new Exception(info); } }
/// <summary> /// 从FTP服务器下载文件,指定本地路径和本地文件名 /// </summary> /// <param name="remoteFile">远程文件名</param> /// <param name="localFile">保存本地的文件名(包含路径)</param> /// <param name="brokenOpen">是否断点下载</param> /// <param name="overWriteIfExist">如果本地文件存在是否覆盖(只在非断点下载情况下有效)</param> /// <param name="updateProgress">报告进度的处理(第一个参数:拥有者对象,第二个参数:总大小,第三个参数:当前进度,第四个参数:下载速度 /秒)</param> /// <returns>是否下载成功</returns> public bool DownloadFile(string remoteFile, string localFile, bool brokenOpen = false, bool overWriteIfExist = true, Action<object, long, long, double> updateProgress = null) { FileInfo file = new FileInfo(localFile); try { state = 0; long size = 0; if (brokenOpen) { if (file.Exists) { size = file.Length; } } else { if (file.Exists) { if (overWriteIfExist) { file.Delete(); } else { throw new Exception("本地文件已存在:" + localFile); } } } long remoteFileSize = GetFileSize(remoteFile); //获取服务器上文件大小 if (remoteFileSize < 0) { remoteFileSize = 0; //文件不存在 } init(remoteFile); ftpReq.ContentOffset = size; ftpReq.Method = WebRequestMethods.Ftp.DownloadFile; using (FtpWebResponse response = (FtpWebResponse)ftpReq.GetResponse()) { using (Stream ftpStream = response.GetResponseStream()) { DateTime dtBegin = DateTime.Now; long totalDownloadedByte = size; int readCount; readCount = ftpStream.Read(buffer, 0, BLOCK_SIZE); using (FileStream outputStream = new FileStream(localFile, FileMode.Append)) while (readCount > 0) { if (state > 0) break; totalDownloadedByte += readCount; outputStream.Write(buffer, 0, readCount); TimeSpan ts = DateTime.Now.Subtract(dtBegin); readCount = ftpStream.Read(buffer, 0, BLOCK_SIZE); double speed = 0; if (ts.Seconds>0) { speed = (totalDownloadedByte - size) / ts.Seconds; } TotalSize = remoteFileSize; CompleteSize = totalDownloadedByte; Speed = speed; updateProgress?.Invoke(Owner, remoteFileSize, totalDownloadedByte, speed);//更新进度条 } } } return true; } catch (Exception ex) { string info = "下载文件失败:" + ex.Message; LogLocal.log().SaveLog(new LogEntity(info, LogType.Plat, LogLevel.ERROR)); throw new Exception(info); } finally { if (state == 2) { file.Delete(); } } }
/// <summary> /// 上传文件到FTP服务器(断点续传) /// </summary> /// <param name="localFile">本地文件全路径名称</param> /// <param name="remoteFile">远程文件</param> /// <param name="brokenOpen ">是否支持断点续传,默认不使用断点续传</param> /// <param name="updateProgress">报告进度的处理(第一个参数:拥有者对象,第二个参数:总大小,第三个参数:当前进度,第四个参数:下载速度 /秒)</param> /// <returns></returns> public bool UploadFile(string localFile, string remoteFile, bool brokenOpen = false, Action<object, long, long, double> updateProgress = null) { try { state = 0; AutoCreateDir(remoteFile); FileInfo fileInf = new FileInfo(localFile); long fileSize = fileInf.Length; long remoteFileSize = GetFileSize(remoteFile); if (remoteFileSize < 0) { remoteFileSize = 0; //文件不存在 } long startByte = 0; if (brokenOpen) { if (remoteFileSize > fileSize) { //服务器上文件比本地还要大,说明出异常了 throw new Exception("服务器文件大小出现异常,请检查后重新上传!"); } startByte = remoteFileSize; } else { if (remoteFileSize > 0) { DeletFile(remoteFile); } remoteFileSize = 0; } init(remoteFile); ftpReq.Method = brokenOpen ? WebRequestMethods.Ftp.AppendFile : WebRequestMethods.Ftp.UploadFile; ftpReq.ContentLength = fileInf.Length; using (FileStream fs = fileInf.OpenRead()) { using (Stream strm = ftpReq.GetRequestStream()) { DateTime dtBegin = DateTime.Now; fs.Seek(startByte, 0); int contentLen = fs.Read(buffer, 0, BLOCK_SIZE); TotalSize = fileSize; CompleteSize = startByte; if (contentLen == 0) { updateProgress?.Invoke(Owner, fileSize, startByte, 0);//更新进度条 } // 流内容没有结束 while (contentLen != 0) { if (state > 0) break; // 把内容从file stream 写入 upload stream startByte += contentLen; strm.Write(buffer, 0, contentLen); contentLen = fs.Read(buffer, 0, BLOCK_SIZE); TimeSpan ts = DateTime.Now.Subtract(dtBegin); double speed = 0; if (ts.Seconds > 0) { speed = (startByte - remoteFileSize) / ts.Seconds; } Speed = speed; updateProgress?.Invoke(Owner, fileSize, startByte, speed);//更新进度条 } } } return true; } catch (Exception ex) { string info = "上传文件失败:" + ex.Message; LogLocal.log().SaveLog(new LogEntity(info, LogType.Plat, LogLevel.ERROR)); throw new Exception(info); } finally { if (state == 2) { DeletFile(remoteFile); } } }
private void OnDebug(CurlInfoType infoType, string msg, int size, object extraData) { LogLocal.log().SaveLog(new LogEntity("CURL-DEBUG:" + msg, LogType.Plat, LogLevel.DEBUG)); }