zoukankan      html  css  js  c++  java
  • C#创建window服务; window服务FTP自动登录和下载;window服务配置Log4Net;读文件插入SQLServer数据库

    第一部分:使用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("
    ");
                        line = reader.ReadLine();
                    }
                    result.Remove(result.ToString().LastIndexOf("
    "), 1);
                    reader.Close();
                    response.Close();
                    return result.ToString().Split('
    ');
                //}
                //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("
    ");
                            }
                        }
                        else
                        {
                            result.Append(line);
                            result.Append("
    ");
                        }
                        line = reader.ReadLine();
                    }
                    result.Remove(result.ToString().LastIndexOf('
    '), 1);
                    reader.Close();
                    response.Close();
                    return result.ToString().Split('
    ');
                //}
                //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() + "
    ";
                    }
                    else if (str.Trim().Substring(0, 1).ToUpper() == "D")
                    {
                        /*判断 Unix 风格*/
                        string dir = str.Substring(54).Trim();
                        if (dir != "." && dir != "..")
                        {
                            m += dir + "
    ";
                        }
                    }
                }
    
                char[] n = new char[] { '
    ' };
                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="&quot;Logs_&quot;yyyyMMdd&quot;.txt&quot;" />
      <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:ftpdata" />
        <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=&quot;data source=.;initial catalog=FarmWeather;persist security info=True;user id=sa;password=yjcd8923459565;MultipleActiveResultSets=True;App=EntityFramework&quot;" 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

  • 相关阅读:
    POJ1321 棋盘问题
    HDU1234 开门人和关门人(解法二)
    HDU1234 开门人和关门人(解法二)
    HDU1996 汉诺塔VI
    HDU1996 汉诺塔VI
    HDU1013 POJ1519 Digital Roots(解法二)
    HDU1013 POJ1519 Digital Roots(解法二)
    HDU4548 美素数
    HDU4548 美素数
    POJ3751 时间日期格式转换【日期计算】
  • 原文地址:https://www.cnblogs.com/hao-1234-1234/p/13958037.html
Copyright © 2011-2022 走看看