第一部分:使用C#創建Windows服務
轉載來源 https://www.cnblogs.com/cncc/p/7170951.html
核心操作
1、新建一個Windows Service,並將項目名稱改爲“MyWindowsService”,如下圖所示:
2、在解決方案資源管理器內將Service1.cs改爲MyService1.cs後並點擊“查看代碼”圖標按鈕進入代碼編輯器界面,如下圖所示:
4、雙擊項目“MyWindowsService”進入“MyService”設計界面,在空白位置右擊鼠標彈出上下文菜單,選中“添加安裝程序”,如下圖所示:
5、此時軟件會生成兩個組件,分別爲“serviceInstaller1”及“serviceProcessInstaller1”,如下圖所示:
6、點擊“serviceInstaller1”,在“屬性”窗體將ServiceName改爲MyService,Description改爲我的服務,StartType保持爲Manual,如下圖所示:
7、點擊“serviceProcessInstaller1”,在“屬性”窗體將Account改爲LocalSystem(服務屬性系統級別),如下圖所示:
8、鼠標右鍵點擊項目“MyWindowsService”,在彈出的上下文菜單中選擇“生成”按鈕,如下圖所示:
9、至此,Windows服務已經創建完畢。
第二部分:c# FTP操作類
轉載來源 https://www.cnblogs.com/swtseaman/archive/2011/03/29/1998611.html
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; //using System.Windows.Forms; using System.Globalization; namespace FTPLib { public class FtpWeb { string ftpServerIP; string ftpRemotePath; string ftpUserID; string ftpPassword; string ftpURI; /// <summary> /// 連接FTP /// </summary> /// <param name="FtpServerIP">FTP連接地址</param> /// <param name="FtpRemotePath">指定FTP連接成功後的當前目錄, 如果不指定即默認爲根目錄</param> /// <param name="FtpUserID">用戶名</param> /// <param name="FtpPassword">密碼</param> public FtpWeb(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword) { ftpServerIP = FtpServerIP; ftpRemotePath = FtpRemotePath; ftpUserID = FtpUserID; ftpPassword = FtpPassword; if (ftpRemotePath != "") { ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; } else { ftpURI = "ftp://" + ftpServerIP + "/"; } } /// <summary> /// 下載 /// </summary> /// <param name="filePath">下載後文件存放位置</param> /// <param name="fileName">文件名稱</param> public bool Download(string filePath, string fileName) { FtpWebRequest reqFTP; bool judge = false; //try //{ FileStream outputStream = new FileStream(filePath+"\\" + fileName, FileMode.Create); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.KeepAlive = false; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); long cl = response.ContentLength; int bufferSize = 2048; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); judge = true; //} //catch (Exception ex) //{ // Insert_Standard_ErrorLog.Insert("FtpWeb", "Download Error --> " + ex.Message); //} return judge; } #region 沒用上的方法,使用時註釋try catch,把異常拋給上一級處理 /// <summary> /// 上傳 /// </summary> /// <param name="filename"></param> public void Upload(string filename) { FileInfo fileInf = new FileInfo(filename); string uri = ftpURI + fileInf.Name; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.UseBinary = true; reqFTP.ContentLength = fileInf.Length; int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; FileStream fs = fileInf.OpenRead(); //try //{ Stream strm = reqFTP.GetRequestStream(); contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } strm.Close(); fs.Close(); //} //catch (Exception ex) //{ // Insert_Standard_ErrorLog.Insert("FtpWeb", "Upload Error --> " + ex.Message); //} } /// <summary> /// 刪除文件 /// </summary> /// <param name="fileName"></param> public void Delete(string fileName) { //try //{ string uri = ftpURI + fileName; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; string result = String.Empty; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); long size = response.ContentLength; Stream datastream = response.GetResponseStream(); StreamReader sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); datastream.Close(); response.Close(); //} //catch (Exception ex) //{ // Insert_Standard_ErrorLog.Insert("FtpWeb", "Delete Error --> " + ex.Message + " 文件名:" + fileName); //} } /// <summary> /// 刪除文件夾 /// </summary> /// <param name="folderName"></param> public void RemoveDirectory(string folderName) { //try //{ string uri = ftpURI + folderName; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory; string result = String.Empty; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); long size = response.ContentLength; Stream datastream = response.GetResponseStream(); StreamReader sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); datastream.Close(); response.Close(); //} //catch (Exception ex) //{ // Insert_Standard_ErrorLog.Insert("FtpWeb", "Delete Error --> " + ex.Message + " 文件名:" + folderName); //} } /// <summary> /// 獲取當前目錄下明細(包含文件和文件夾) /// </summary> /// <returns></returns> public string[] GetFilesDetailList() { string[] downloadFiles; //try //{ StringBuilder result = new StringBuilder(); FtpWebRequest ftp; ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI)); ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword); ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; WebResponse response = ftp.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); //while (reader.Read() > 0) //{ //} string line = reader.ReadLine(); //line = reader.ReadLine(); //line = reader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = reader.ReadLine(); } result.Remove(result.ToString().LastIndexOf("\n"), 1); reader.Close(); response.Close(); return result.ToString().Split('\n'); //} //catch (Exception ex) //{ // downloadFiles = null; // Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFilesDetailList Error --> " + ex.Message); // return downloadFiles; //} } /// <summary> /// 獲取當前目錄下文件列表(僅文件) /// </summary> /// <returns></returns> public string[] GetFileList(string mask) { string[] downloadFiles; StringBuilder result = new StringBuilder(); FtpWebRequest reqFTP; //try //{ reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI)); reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.Method = WebRequestMethods.Ftp.ListDirectory; WebResponse response = reqFTP.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default); string line = reader.ReadLine(); while (line != null) { if (mask.Trim() != string.Empty && mask.Trim() != "*.*") { string mask_ = mask.Substring(0, mask.IndexOf("*")); if (line.Substring(0, mask_.Length) == mask_) { result.Append(line); result.Append("\n"); } } else { result.Append(line); result.Append("\n"); } line = reader.ReadLine(); } result.Remove(result.ToString().LastIndexOf('\n'), 1); reader.Close(); response.Close(); return result.ToString().Split('\n'); //} //catch (Exception ex) //{ // downloadFiles = null; // if (ex.Message.Trim() != "遠程服務器返回錯誤: (550) 文件不可用(例如,未找到文件,無法訪問文件)。") // { // Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFileList Error --> " + ex.Message.ToString()); // } // return downloadFiles; //} } /// <summary> /// 獲取當前目錄下所有的文件夾列表(僅文件夾) /// </summary> /// <returns></returns> public string[] GetDirectoryList() { string[] drectory = GetFilesDetailList(); string m = string.Empty; foreach (string str in drectory) { int dirPos = str.IndexOf("<DIR>"); if (dirPos > 0) { /*判斷 Windows 風格*/ m += str.Substring(dirPos + 5).Trim() + "\n"; } else if (str.Trim().Substring(0, 1).ToUpper() == "D") { /*判斷 Unix 風格*/ string dir = str.Substring(54).Trim(); if (dir != "." && dir != "..") { m += dir + "\n"; } } } char[] n = new char[] { '\n' }; return m.Split(n); } /// <summary> /// 判斷當前目錄下指定的子目錄是否存在 /// </summary> /// <param name="RemoteDirectoryName">指定的目錄名</param> public bool DirectoryExist(string RemoteDirectoryName) { string[] dirList = GetDirectoryList(); foreach (string str in dirList) { if (str.Trim() == RemoteDirectoryName.Trim()) { return true; } } return false; } /// <summary> /// 判斷當前目錄下指定的文件是否存在 /// </summary> /// <param name="RemoteFileName">遠程文件名</param> public bool FileExist(string RemoteFileName) { string[] fileList = GetFileList("*.*"); foreach (string str in fileList) { if (str.Trim() == RemoteFileName.Trim()) { return true; } } return false; } /// <summary> /// 創建文件夾 /// </summary> /// <param name="dirName"></param> public void MakeDir(string dirName) { FtpWebRequest reqFTP; //try //{ // dirName = name of the directory to create. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName)); reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); //} //catch (Exception ex) //{ // Insert_Standard_ErrorLog.Insert("FtpWeb", "MakeDir Error --> " + ex.Message); //} } /// <summary> /// 獲取指定文件大小 /// </summary> /// <param name="filename"></param> /// <returns></returns> public long GetFileSize(string filename) { FtpWebRequest reqFTP; long fileSize = 0; //try //{ reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename)); reqFTP.Method = WebRequestMethods.Ftp.GetFileSize; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); fileSize = response.ContentLength; ftpStream.Close(); response.Close(); //} //catch (Exception ex) //{ // Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFileSize Error --> " + ex.Message); //} return fileSize; } /// <summary> /// 改名 /// </summary> /// <param name="currentFilename"></param> /// <param name="newFilename"></param> public void ReName(string currentFilename, string newFilename) { FtpWebRequest reqFTP; //try //{ reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename)); reqFTP.Method = WebRequestMethods.Ftp.Rename; reqFTP.RenameTo = newFilename; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); //} //catch (Exception ex) //{ // Insert_Standard_ErrorLog.Insert("FtpWeb", "ReName Error --> " + ex.Message); //} } /// <summary> /// 移動文件 /// </summary> /// <param name="currentFilename"></param> /// <param name="newFilename"></param> public void MovieFile(string currentFilename, string newDirectory) { ReName(currentFilename, newDirectory); } /// <summary> /// 切換當前目錄 /// </summary> /// <param name="DirectoryName"></param> /// <param name="IsRoot">true 絕對路徑 false 相對路徑</param> public void GotoDirectory(string DirectoryName, bool IsRoot) { if (IsRoot) { ftpRemotePath = DirectoryName; } else { ftpRemotePath += DirectoryName + "/"; } ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/"; } /// <summary> /// 刪除訂單目錄 /// </summary> /// <param name="ftpServerIP">FTP 主機地址</param> /// <param name="folderToDelete">FTP 用戶名</param> /// <param name="ftpUserID">FTP 用戶名</param> /// <param name="ftpPassword">FTP 密碼</param> public static void DeleteOrderDirectory(string ftpServerIP, string folderToDelete, string ftpUserID, string ftpPassword) { //try //{ if (!string.IsNullOrEmpty(ftpServerIP) && !string.IsNullOrEmpty(folderToDelete) && !string.IsNullOrEmpty(ftpUserID) && !string.IsNullOrEmpty(ftpPassword)) { FtpWeb fw = new FtpWeb(ftpServerIP, folderToDelete, ftpUserID, ftpPassword); //進入訂單目錄 fw.GotoDirectory(folderToDelete, true); //獲取規格目錄 string[] folders = fw.GetDirectoryList(); foreach (string folder in folders) { if (!string.IsNullOrEmpty(folder) || folder != "") { //進入訂單目錄 string subFolder = folderToDelete + "/" + folder; fw.GotoDirectory(subFolder, true); //獲取文件列表 string[] files = fw.GetFileList("*.*"); if (files != null) { //刪除文件 foreach (string file in files) { fw.Delete(file); } } //刪除沖印規格文件夾 fw.GotoDirectory(folderToDelete, true); fw.RemoveDirectory(folder); } } //刪除訂單文件夾 string parentFolder = folderToDelete.Remove(folderToDelete.LastIndexOf('/')); string orderFolder = folderToDelete.Substring(folderToDelete.LastIndexOf('/') + 1); fw.GotoDirectory(parentFolder, true); fw.RemoveDirectory(orderFolder); } else { throw new Exception("FTP 及路徑不能爲空!"); } //} //catch (Exception ex) //{ // throw new Exception("刪除訂單時發生錯誤,錯誤信息爲:" + ex.Message); //} } #endregion } public class Insert_Standard_ErrorLog { public static void Insert(string x, string y) { } } }
第三部分:window服務中配置值Log4Net
轉載來源 https://www.cnblogs.com/Can-daydayup/p/10223239.html
https://www.cnblogs.com/skyheaving/p/12294241.html
思維導航:
文章正文:
一、使用背景:
C#window服務下添加一個日誌記錄程序集(Log4Net.dll)
二、添加和使用步驟如下:
下載並引入Log4Net.dll程序集到項目中
下載地址:http://logging.apache.org/log4net/download_log4net.cgi
在App.Config中添加對應的節點
<!--重點configsections必須是第一個節點1og4net配置--> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections>
在App.Config中添加Log4Net.dll初始化信息(主要一些按照什麼格式存儲,存儲位置的配置)
<log4net> <!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL --> <!-- Set root logger level to ERROR and its appenders --> <root> <level value="ALL" /> <appender-ref ref="SysAppender" /> </root> <!-- Print only messages of level DEBUG or above in the packages --> <logger name="WebLogger"> <level value="DEBUG" /> </logger> <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net"> <!--日誌文件夾名稱--> <param name="File" value="ProJectsLogs/" /> <param name="AppendToFile" value="true" /> <param name="RollingStyle" value="Date" /> <param name="DatePattern" value=""Logs_"yyyyMMdd".txt"" /> <param name="StaticLogFileName" value="false" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> </layout> </appender> <appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net"> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> </layout> </appender> </log4net>
實際應用中App.config改動:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <log4net> <root> <appender-ref ref="RollingLogFileAppender" /> <appender-ref ref="ConsoleAppender" /> </root> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="[%date] %level [%thread][%c{1}:%line] - %m%n" /> </layout> </appender> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--日誌存放位置 ~/..--> <param name="File" value="logs\\" /> <!--追加到文本末尾--> <param name="AppendToFile" value="true" /> <!--最多產生的日誌文件數,超過則只保留最新的n個。設定值value="-1"爲不限文件數--> <param name="MaxSizeRollBackups" value="50" /> <!--最大文件大小--> <param name="MaximumFileSize" value="5MB"/> <param name="RollingStyle" value="Date" /> <!--文件命名方式--> <param name="DatePattern" value="yyyy-MM-dd'.log'" /> <param name="StaticLogFileName" value="false" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="[%date] %level [%thread][%c{1}:%line] %n%m%n" /> </layout> </appender> </log4net> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup> <appSettings> <add key="website" value="www.baidu.com" /> <add key="user" value="UserName" /> <add key="password" value="Password" /> <add key="localFilePath" value="D:ftp\data" /> <add key="nameList" value="AWS_30min.dat,AWS_10min.dat,TMS_10min.dat,TMS_30min.dat" /> </appSettings> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework> <connectionStrings> <add name="FarmWeatherEntities" connectionString="metadata=res://*/FarmWeather.csdl|res://*/FarmWeather.ssdl|res://*/FarmWeather.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=FarmWeather;persist security info=True;user id=sa;password=yjcd8923459565;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> </connectionStrings> </configuration>
在AssemblyInfo.cs:配置文件中讀取配置Log4net.dll
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
使用Log4Net.Dll記錄日誌
//首先實例化Log4net private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //使用記錄信息 log.Debug("Debug", new Exception("Debug")); log.Info("Info", new Exception("Info")); log.Warn("Warn", new Exception("Warn")); log.Error("Error", new Exception("Error")); log.Fatal("Fatal", new Exception("Fatal"));
實際應用中可以封裝成一個類
public class LogManage { private static readonly ILog logger = LogManager.GetLogger(typeof(LogManage)); static LogManage() { BasicConfigurator.Configure(); } public static void Error(Exception ex) { logger.Error(ex.Message, ex); } public static void Error(string msg) { logger.Error(msg); } public static void Info(string msg) { logger.Info(msg); } }
第四部分:插入SQLserver數據庫
public class ImportDataByModel { public DateTime? AWS30minMaxDate() { DateTime? date = null; using (var dbfw = new FarmWeatherEntities()) { date = dbfw.AWS30min.Select(d => (DateTime?)d.TIMESTAMP).Max(); } return date; } public DateTime? AWS10minMaxDate() { DateTime? date = null; using (var dbfw = new FarmWeatherEntities()) { date = dbfw.AWS10min.Select(d => (DateTime?)d.TIMESTAMP).Max(); } return date; } public DateTime? TMS30minMaxDate() { DateTime? date = null; using (var dbfw = new FarmWeatherEntities()) { date = dbfw.TMS30min.Select(d => (DateTime?)d.TIMESTAMP).Max(); } return date; } public DateTime? TMS10minMaxDate() { DateTime? date = null; using (var dbfw = new FarmWeatherEntities()) { date = dbfw.TMS10min.Select(d => (DateTime?)d.TIMESTAMP).Max(); } return date; } public void ImportAWS30min(List<string> lines) { var list = new List<AWS30min>() { }; //try //{ if (lines != null && lines.Count > 4) { var maxDate = AWS30minMaxDate(); string[] columnNameArray = lines[1].Split(','); //行數 for (int i = 4; i < lines.Count; i++) { //列數 string[] temp = lines[i].Split(','); if (temp != null && temp.Length >= 30) { var info = new AWS30min(); var temp0 = temp[0].Replace("\"", ""); var dateTime= Convert.ToDateTime(temp0); info.TIMESTAMP = dateTime; info.RECORD = Convert.ToDouble(temp[1]); if (temp[2] != "\"NAN\"") { info.batt_volt_Min = Convert.ToDouble(temp[2]); } if (temp[3] != "\"NAN\"") { info.PTemp = Convert.ToDouble(temp[3]); } if (temp[4] != "\"NAN\"") { info.TA_Avg = Convert.ToDouble(temp[4]); } if (temp[5] != "\"NAN\"") { info.RH_Avg = Convert.ToDouble(temp[5]); } if (temp[6] != "\"NAN\"") { info.DR_Avg = Convert.ToDouble(temp[6]); } if (temp[7] != "\"NAN\"") { info.UR_Avg = Convert.ToDouble(temp[7]); } if (temp[8] != "\"NAN\"") { info.DLR_Avg = Convert.ToDouble(temp[8]); } if (temp[9] != "\"NAN\"") { info.ULR_Avg = Convert.ToDouble(temp[9]); } //if (temp[10] != "\"NAN\"") //{ // info.cnr4_T_C_Avg = Convert.ToDouble(temp[10]); //} //if (temp[11] != "\"NAN\"") //{ // info.cnr4_T_K_Avg = Convert.ToDouble(temp[11]); //} //if (temp[12] != "\"NAN\"") //{ // info.Rn_Avg = Convert.ToDouble(temp[12]); //} //if (temp[13] != "\"NAN\"") //{ // info.albedo_Avg = Convert.ToDouble(temp[13]); //} if (temp[14] != "\"NAN\"") { info.Press_Avg = Convert.ToDouble(temp[14]); } if (temp[15] != "\"NAN\"") { info.GS_2cm_Avg = Convert.ToDouble(temp[15]); } if (temp[16] != "\"NAN\"") { info.GS_5cm_Avg = Convert.ToDouble(temp[16]); } if (temp[17] != "\"NAN\"") { info.PAR_Avg = Convert.ToDouble(temp[17]); } if (temp[18] != "\"NAN\"") { info.WS_Avg = Convert.ToDouble(temp[18]); } if (temp[19] != "\"NAN\"") { info.WD = Convert.ToDouble(temp[19]); } if (temp[20] != "\"NAN\"") { info.TargTempC_Avg = Convert.ToDouble(temp[20]); } if (temp[21] != "\"NAN\"") { info.SBTempC_Avg = Convert.ToDouble(temp[21]); } if (temp[22] != "\"NAN\"") { info.UV_Avg = Convert.ToDouble(temp[22]); } if (temp[23] != "\"NAN\"") { info.Rain_Tot = Convert.ToDouble(temp[23]); } if (temp[24] != "\"NAN\"") { info.Sun_Hour_Tot = Convert.ToDouble(temp[24]); } if (temp[25] != "\"NAN\"") { info.dir_Ra_Avg = Convert.ToDouble(temp[25]); } if (temp[26] != "\"NAN\"") { info.Depth_Avg = Convert.ToDouble(temp[26]); } if (temp[27] != "\"NAN\"") { info.TS_Solinst = Convert.ToDouble(temp[27]); } if (temp[28] != "\"NAN\"") { info.Depth_Solinst = Convert.ToDouble(temp[28]); } if (temp[29] != "\"NAN\"") { info.EC_Solinst = Convert.ToDouble(temp[29]); } if (maxDate != null) { if (dateTime > maxDate) { list.Add(info); } }else { list.Add(info); } } } if (list.Count > 0) { list = list.DistinctByOneField(d => d.TIMESTAMP).ToList(); using (var dbfw = new FarmWeatherEntities()) { dbfw.AWS30min.AddRange(list); dbfw.SaveChanges(); } } } //} // catch (Exception ex) // { // while (ex.InnerException != null) // { // ex = ex.InnerException; // //若重複錯誤,則逐條遍歷。 // if (ex.Message.Contains("IX_")) // { // foreach (var myObj in list) // { // try // { // using (var dbfw = new FarmWeatherEntities()) // { // list = list.DistinctByOneField(d => d.TIMESTAMP).ToList(); // db.AWS30min.AddRange(list); // db.SaveChanges(); // } // } // catch (Exception ex2) // { // } // } // } // } // } } public void ImportAWS10min(List<string> lines) { if (lines != null && lines.Count > 4) { var maxDate = AWS10minMaxDate(); string[] columnNameArray = lines[1].Split(','); var list = new List<AWS10min>() { }; //行數 for (int i = 4; i < lines.Count; i++) { //列數 string[] temp = lines[i].Split(','); if (temp != null && temp.Length >=30) { var info = new AWS10min(); var temp0 = temp[0].Replace("\"", ""); var dateTime = Convert.ToDateTime(temp0); info.TIMESTAMP = dateTime; info.RECORD = Convert.ToDouble(temp[1]); if (temp[2] != "\"NAN\"") { info.batt_volt_Min = Convert.ToDouble(temp[2]); } if (temp[3] != "\"NAN\"") { info.PTemp = Convert.ToDouble(temp[3]); } if (temp[4] != "\"NAN\"") { info.TA_Avg = Convert.ToDouble(temp[4]); } if (temp[5] != "\"NAN\"") { info.RH_Avg = Convert.ToDouble(temp[5]); } if (temp[6] != "\"NAN\"") { info.DR_Avg = Convert.ToDouble(temp[6]); } if (temp[7] != "\"NAN\"") { info.UR_Avg = Convert.ToDouble(temp[7]); } if (temp[8] != "\"NAN\"") { info.DLR_Avg = Convert.ToDouble(temp[8]); } if (temp[9] != "\"NAN\"") { info.ULR_Avg = Convert.ToDouble(temp[9]); } //if (temp[10] != "\"NAN\"") //{ // info.cnr4_T_C_Avg = Convert.ToDouble(temp[10]); //} //if (temp[11] != "\"NAN\"") //{ // info.cnr4_T_K_Avg = Convert.ToDouble(temp[11]); //} //if (temp[12] != "\"NAN\"") //{ // info.Rn_Avg = Convert.ToDouble(temp[12]); //} //if (temp[13] != "\"NAN\"") //{ // info.albedo_Avg = Convert.ToDouble(temp[13]); //} if (temp[14] != "\"NAN\"") { info.Press_Avg = Convert.ToDouble(temp[14]); } if (temp[15] != "\"NAN\"") { info.GS_2cm_Avg = Convert.ToDouble(temp[15]); } if (temp[16] != "\"NAN\"") { info.GS_5cm_Avg = Convert.ToDouble(temp[16]); } if (temp[17] != "\"NAN\"") { info.PAR_Avg = Convert.ToDouble(temp[17]); } if (temp[18] != "\"NAN\"") { info.WS_Avg = Convert.ToDouble(temp[18]); } if (temp[19] != "\"NAN\"") { info.WD = Convert.ToDouble(temp[19]); } if (temp[20] != "\"NAN\"") { info.TargTempC_Avg = Convert.ToDouble(temp[20]); } if (temp[21] != "\"NAN\"") { info.SBTempC_Avg = Convert.ToDouble(temp[21]); } if (temp[22] != "\"NAN\"") { info.UV_Avg = Convert.ToDouble(temp[22]); } if (temp[23] != "\"NAN\"") { info.Rain_Tot = Convert.ToDouble(temp[23]); } if (temp[24] != "\"NAN\"") { info.Sun_Hour_Tot = Convert.ToDouble(temp[24]); } if (temp[25] != "\"NAN\"") { info.dir_Ra_Avg = Convert.ToDouble(temp[25]); } if (temp[26] != "\"NAN\"") { info.Depth_Avg = Convert.ToDouble(temp[26]); } if (temp[27] != "\"NAN\"") { info.TS_Solinst = Convert.ToDouble(temp[27]); } if (temp[28] != "\"NAN\"") { info.Depth_Solinst = Convert.ToDouble(temp[28]); } if (temp[29] != "\"NAN\"") { info.EC_Solinst = Convert.ToDouble(temp[29]); } if (maxDate != null) { if (dateTime > maxDate) { list.Add(info); } } else { list.Add(info); } } } if (list.Count > 0) { var list2 = list.DistinctByOneField(d => d.TIMESTAMP).ToList(); using (var dbfw=new FarmWeatherEntities()) { dbfw.AWS10min.AddRange(list2); dbfw.SaveChanges(); } } } } public void ImportTMS10min(List<string> lines) { var list = new List<TMS10min>() { }; if (lines != null && lines.Count > 4) { var maxDate = TMS10minMaxDate(); string[] columnNameArray = lines[1].Split(','); //行數 for (int i = 4; i < lines.Count; i++) { //列數 string[] temp = lines[i].Split(','); if (temp != null && temp.Length >= 24) { var info = new TMS10min(); var temp0 = temp[0].Replace("\"", ""); var dateTime = Convert.ToDateTime(temp0); info.TIMESTAMP = dateTime; info.RECORD = Convert.ToDouble(temp[1]); if (temp[2] != "\"NAN\"") { info.TS_0cm_Avg = Convert.ToDouble(temp[2]); } if (temp[3] != "\"NAN\"") { info.MS_5cm_Avg = Convert.ToDouble(temp[3]); } if (temp[4] != "\"NAN\"") { info.EC_5cm_Avg = Convert.ToDouble(temp[4]); } if (temp[5] != "\"NAN\"") { info.TS_5cm_Avg = Convert.ToDouble(temp[5]); } if (temp[6] != "\"NAN\"") { info.MS_10cm_Avg = Convert.ToDouble(temp[6]); } if (temp[7] != "\"NAN\"") { info.EC_10cm_Avg = Convert.ToDouble(temp[7]); } if (temp[8] != "\"NAN\"") { info.TS_10cm_Avg = Convert.ToDouble(temp[8]); } if (temp[9] != "\"NAN\"") { info.MS_20cm_Avg = Convert.ToDouble(temp[9]); } if (temp[10] != "\"NAN\"") { info.EC_20cm_Avg = Convert.ToDouble(temp[10]); } if (temp[11] != "\"NAN\"") { info.TS_20cm_Avg = Convert.ToDouble(temp[11]); } if (temp[12] != "\"NAN\"") { info.MS_40cm_Avg = Convert.ToDouble(temp[12]); } if (temp[13] != "\"NAN\"") { info.EC_40cm_Avg = Convert.ToDouble(temp[13]); } if (temp[14] != "\"NAN\"") { info.TS_40cm_Avg = Convert.ToDouble(temp[14]); } if (temp[15] != "\"NAN\"") { info.MS_60cm_Avg = Convert.ToDouble(temp[15]); } if (temp[16] != "\"NAN\"") { info.EC_60cm_Avg = Convert.ToDouble(temp[16]); } if (temp[17] != "\"NAN\"") { info.TS_60cm_Avg = Convert.ToDouble(temp[17]); } if (temp[18] != "\"NAN\"") { info.MS_80cm_Avg = Convert.ToDouble(temp[18]); } if (temp[19] != "\"NAN\"") { info.EC_80cm_Avg = Convert.ToDouble(temp[19]); } if (temp[20] != "\"NAN\"") { info.TS_80cm_Avg = Convert.ToDouble(temp[20]); } if (temp[21] != "\"NAN\"") { info.MS_100cm_Avg = Convert.ToDouble(temp[21]); } if (temp[22] != "\"NAN\"") { info.EC_100cm_Avg = Convert.ToDouble(temp[22]); } if (temp[23] != "\"NAN\"") { info.TS_100cm_Avg = Convert.ToDouble(temp[23]); } if (maxDate != null) { if (dateTime > maxDate) { list.Add(info); } } else { list.Add(info); } } } if (list.Count > 0) { list = list.DistinctByOneField(d => d.TIMESTAMP).ToList(); using (var dbfw = new FarmWeatherEntities()) { dbfw.TMS10min.AddRange(list); dbfw.SaveChanges(); } } } } public void ImportTMS30min(List<string> lines) { if (lines != null && lines.Count > 4) { var maxDate = TMS30minMaxDate(); string[] columnNameArray = lines[1].Split(','); var list = new List<TMS30min>() { }; //行數 for (int i = 4; i < lines.Count; i++) { //列數 string[] temp = lines[i].Split(','); if (temp != null && temp.Length >= 24) { var info = new TMS30min(); var temp0 = temp[0].Replace("\"", ""); var dateTime = Convert.ToDateTime(temp0); info.TIMESTAMP = dateTime; info.RECORD = Convert.ToDouble(temp[1]); if (temp[2] != "\"NAN\"") { info.TS_0cm_Avg = Convert.ToDouble(temp[2]); } if (temp[3] != "\"NAN\"") { info.MS_5cm_Avg = Convert.ToDouble(temp[3]); } if (temp[4] != "\"NAN\"") { info.EC_5cm_Avg = Convert.ToDouble(temp[4]); } if (temp[5] != "\"NAN\"") { info.TS_5cm_Avg = Convert.ToDouble(temp[5]); } if (temp[6] != "\"NAN\"") { info.MS_10cm_Avg = Convert.ToDouble(temp[6]); } if (temp[7] != "\"NAN\"") { info.EC_10cm_Avg = Convert.ToDouble(temp[7]); } if (temp[8] != "\"NAN\"") { info.TS_10cm_Avg = Convert.ToDouble(temp[8]); } if (temp[9] != "\"NAN\"") { info.MS_20cm_Avg = Convert.ToDouble(temp[9]); } if (temp[10] != "\"NAN\"") { info.EC_20cm_Avg = Convert.ToDouble(temp[10]); } if (temp[11] != "\"NAN\"") { info.TS_20cm_Avg = Convert.ToDouble(temp[11]); } if (temp[12] != "\"NAN\"") { info.MS_40cm_Avg = Convert.ToDouble(temp[12]); } if (temp[13] != "\"NAN\"") { info.EC_40cm_Avg = Convert.ToDouble(temp[13]); } if (temp[14] != "\"NAN\"") { info.TS_40cm_Avg = Convert.ToDouble(temp[14]); } if (temp[15] != "\"NAN\"") { info.MS_60cm_Avg = Convert.ToDouble(temp[15]); } if (temp[16] != "\"NAN\"") { info.EC_60cm_Avg = Convert.ToDouble(temp[16]); } if (temp[17] != "\"NAN\"") { info.TS_60cm_Avg = Convert.ToDouble(temp[17]); } if (temp[18] != "\"NAN\"") { info.MS_80cm_Avg = Convert.ToDouble(temp[18]); } if (temp[19] != "\"NAN\"") { info.EC_80cm_Avg = Convert.ToDouble(temp[19]); } if (temp[20] != "\"NAN\"") { info.TS_80cm_Avg = Convert.ToDouble(temp[20]); } if (temp[21] != "\"NAN\"") { info.MS_100cm_Avg = Convert.ToDouble(temp[21]); } if (temp[22] != "\"NAN\"") { info.EC_100cm_Avg = Convert.ToDouble(temp[22]); } if (temp[23] != "\"NAN\"") { info.TS_100cm_Avg = Convert.ToDouble(temp[23]); } if (maxDate != null) { if (dateTime > maxDate) { list.Add(info); } } else { list.Add(info); } } } if (list.Count > 0) { var list2 = list.DistinctByOneField(d => d.TIMESTAMP).ToList(); using (var dbfw = new FarmWeatherEntities()) { dbfw.TMS30min.AddRange(list2); dbfw.SaveChanges(); } } } } }
實體類
public class AWS30min { public int ID { get; set; } public System.DateTime TIMESTAMP { get; set; } public Nullable<double> RECORD { get; set; } public Nullable<double> batt_volt_Min { get; set; } public Nullable<double> PTemp { get; set; } public Nullable<double> TA_Avg { get; set; } public Nullable<double> RH_Avg { get; set; } public Nullable<double> DR_Avg { get; set; } public Nullable<double> UR_Avg { get; set; } public Nullable<double> DLR_Avg { get; set; } public Nullable<double> ULR_Avg { get; set; } public Nullable<double> Press_Avg { get; set; } public Nullable<double> GS_2cm_Avg { get; set; } public Nullable<double> GS_5cm_Avg { get; set; } public Nullable<double> PAR_Avg { get; set; } public Nullable<double> WS_Avg { get; set; } public Nullable<double> WD { get; set; } public Nullable<double> TargTempC_Avg { get; set; } public Nullable<double> SBTempC_Avg { get; set; } public Nullable<double> UV_Avg { get; set; } public Nullable<double> Rain_Tot { get; set; } public Nullable<double> Sun_Hour_Tot { get; set; } public Nullable<double> dir_Ra_Avg { get; set; } public Nullable<double> Depth_Avg { get; set; } public Nullable<double> TS_Solinst { get; set; } public Nullable<double> Depth_Solinst { get; set; } public Nullable<double> EC_Solinst { get; set; } } public class TMS30min { public int ID { get; set; } public System.DateTime TIMESTAMP { get; set; } public Nullable<double> RECORD { get; set; } public Nullable<double> TS_0cm_Avg { get; set; } public Nullable<double> MS_5cm_Avg { get; set; } public Nullable<double> EC_5cm_Avg { get; set; } public Nullable<double> TS_5cm_Avg { get; set; } public Nullable<double> MS_10cm_Avg { get; set; } public Nullable<double> EC_10cm_Avg { get; set; } public Nullable<double> TS_10cm_Avg { get; set; } public Nullable<double> MS_20cm_Avg { get; set; } public Nullable<double> EC_20cm_Avg { get; set; } public Nullable<double> TS_20cm_Avg { get; set; } public Nullable<double> MS_40cm_Avg { get; set; } public Nullable<double> EC_40cm_Avg { get; set; } public Nullable<double> TS_40cm_Avg { get; set; } public Nullable<double> MS_60cm_Avg { get; set; } public Nullable<double> EC_60cm_Avg { get; set; } public Nullable<double> TS_60cm_Avg { get; set; } public Nullable<double> MS_80cm_Avg { get; set; } public Nullable<double> EC_80cm_Avg { get; set; } public Nullable<double> TS_80cm_Avg { get; set; } public Nullable<double> MS_100cm_Avg { get; set; } public Nullable<double> EC_100cm_Avg { get; set; } public Nullable<double> TS_100cm_Avg { get; set; } }
AWS30min 與AWS10min 相同,TMS30min 與TMS10min 相同。
第五部分整體調用
using FarmWeather.DAL; using FileOperate; using FTPLib; //using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; namespace MyWindowsService { public partial class MyService : ServiceBase { private string website; private string user; private string password; private string localFilePath; private string nameList; private System.Timers.Timer m_Timer; public MyService() { InitializeComponent(); //事件中命名 if (!System.Diagnostics.EventLog.SourceExists("數據獲取服務")) { System.Diagnostics.EventLog.CreateEventSource( "數據獲取服務", "A軟件開發有限公司"); } this.m_EventLog.Source = "數據獲取服務"; m_EventLog.Log = "A軟件開發有限公司"; } #region 服務開關 protected override void OnStart(string[] args) { website = System.Configuration.ConfigurationManager.AppSettings["website"]; user = System.Configuration.ConfigurationManager.AppSettings["user"]; password = System.Configuration.ConfigurationManager.AppSettings["password"]; localFilePath = System.Configuration.ConfigurationManager.AppSettings["localFilePath"]; nameList = System.Configuration.ConfigurationManager.AppSettings["nameList"]; System.Timers.Timer timer = new System.Timers.Timer(); //啓動Timer //timer.Interval = 24*60 * 60 * 1000; timer.Interval = 1 * 60 * 1000;//1分鐘循環一次 timer.AutoReset = true; timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); timer.Start(); m_Timer = timer; } /// <summary> /// 暫停後繼續運行 /// </summary> protected override void OnContinue() { if (this.m_Timer != null) { this.m_Timer.Start(); } base.OnContinue(); } /// <summary> /// 暫停 /// </summary> protected override void OnPause() { if (this.m_Timer != null) { this.m_Timer.Stop(); } base.OnPause(); } protected override void OnStop() { if (this.m_Timer != null) { this.m_Timer.Dispose(); this.m_Timer = null; } this.m_EventLog.WriteEntry("服務停止成功"); } #endregion #region 獲取最新數據 //下載數據方法在一小時內只執行一次。 bool isDownloading = false; private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { var dateTime = DateTime.Now; if (dateTime.Minute >=45) { if (isDownloading == false) { isDownloading = true; try { Import(); LogManage.Info(dateTime.ToString("yyyy-MM-dd:HH:mm:ss")+"導入成功"); } catch (Exception ex) { LogManage.Error(ex); } } } else { isDownloading = false; } } //下載FTP服務器數據,插入數據庫 private void Import() { var ftp = new FtpWeb(website, "", user, password); string[] namelist = nameList.Split(','); //本地保存地址 var filePath = localFilePath; foreach (var name in namelist) { //下載文件 var judge = ftp.Download(filePath, name); if (judge == true) { var inputPath = System.IO.Path.Combine(filePath, name); //讀文件 var lines = FileHelper.ReadList(inputPath); //插入數據庫 var importObj = new ImportDataByModel(); switch (name) { case "AWS_30min.dat": importObj.ImportAWS30min(lines); break; case "AWS_10min.dat": importObj.ImportAWS10min(lines); break; case "TMS_10min.dat": importObj.ImportTMS10min(lines); break; case "TMS_30min.dat": importObj.ImportTMS30min(lines); break; default: break; } } } } #endregion } }
下載成功
數據格式舉例:
入庫成功:
前者是倒入成功時刻,後者是開始導入時刻,可以計算一次導入用時。
常見錯誤:
https://q.cnblogs.com/q/94442/
C# WebRequest出錯:"服務器提交了協議衝突"
webRequest.KeepAlive = false;//設置一下看看
FarmWeather