C#利用CMD来获取触摸屏保存到FTP里的报警信息与操作记录

这篇博客介绍如何使用C#读取PLC触摸屏的报警信息和操作记录,并通过FTP下载相关文件。接着,通过CMD命令将这些文件转换为CSV格式,适用于威纶通触摸屏。代码示例可供需要此类功能的开发者参考。

该Demo尝试利用C#来读取PLC触摸屏的报警信息和操作日志写入工控机并保存
通过访问FTP的链接,在FTP当中将所需要的文件进行拷贝,复制到指定位置,然后
通过CMD来对触摸屏进行格式转换
该方法可直接实现将FTP里面db文件、evt文件等直接转换成CSV文档,至于可以转换哪些格式,请翻阅触摸屏关于存储ftp文件格式的说明

这份代码是以威纶通触摸屏为模板写的,有需要的朋友可以看看
下面展示一些 内联代码片

// An highlighted block
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace cmd
{
    class Program
    {
        #region FTP
        private static string host = null;
        private static string user = null;
        private static string pass = null;
        private static FtpWebRequest ftpRequest = null;
        private static FtpWebResponse ftpResponse = null;
        private static Stream ftpStream = null;
        private static int bufferSize = 8192;

        public static bool BinaryMode = true;

        //创建对象
        public Program(string hostIP, string userName, string password)
        {
            host = hostIP;
            user = userName;
            pass = password;
        }

        //从FTP获取
        public static void get(string remoteFile, string localFile)
        {
            try
            {
                //创建FTP请求,将ftp的链接和文件名传入
                FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
                //使用提供的用户名和密码登录FTP服务器 ,这个用户名和密码在触摸屏的说明文档里
                ftpRequest.Credentials = new NetworkCredential(user, pass);
                ftpRequest.UseBinary = BinaryMode;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                //配置FTP请求的类型
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                //与FTP服务器建立返回通信 
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                //获取FTP服务器的响应流
                ftpStream = ftpResponse.GetResponseStream();
                //打开文件流来写入下载的文件 
                FileStream localFileStream = new FileStream(localFile, FileMode.Create);
                //下载数据的缓冲区
                byte[] byteBuffer = new byte[bufferSize];
                int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                //通过写入缓冲数据来下载文件,直到传输完成 
                try
                {
                    while (bytesRead > 0)
                    {
                        localFileStream.Write(byteBuffer, 0, bytesRead);
                        bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
                //将下面内容关闭,释放资源
                localFileStream.Close();
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            return;
        }
        #endregion
        static void Main(string[] args)
        {
            bool status = false;

            //连接共享文件夹,这里是自己创建的FTP来测试的
            //status = connectState(@"\\192.168.18.100\ftp_test", "DC0455", "8523");
            //if (status)
            //{
            if (File.Exists(@"D:\报警信息\operationlog.db"))
            {
                File.Delete(@"D:\报警信息\operationlog.db");
            }
            //这里是获取db文件的
            Program ftpClient1 = new Program(@"ftp://uploadhis:111111@192.168.250.3/operationlog/", "uploadhis", "111111");
            get("operationlog.db", @"D:\报警信息\operationlog.db");
            //这里是获取evt文件的
			Program ftpClient2 = new Program (@" ftp://uploadhis:111111@192.168.250.3/eventlog/", "uploadhis", "111111");
            getFtpFile($"EL_{DateTime.Now.AddDays(-1).ToString("yyyyMMdd")}.evt", @"D:\报警信息\event.evt");
        }
        /// <summary>
        /// 连接远程共享文件夹
        /// </summary>
        /// <param name="path">远程共享文件夹的路径</param>
        /// <param name="userName">用户名</param>
        /// <param name="passWord">密码</param>
        /// <returns></returns>
        public static bool connectState(string path, string userName, string passWord)
        {
            bool Flag = false;
            Process proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }
                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                if (string.IsNullOrEmpty(errormsg))
                {
                    Flag = true;
                }
                else
                {
                    throw new Exception(errormsg);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }

        /// <summary>
        /// 向远程文件夹保存本地内容,或者从远程文件夹下载文件到本地
        /// </summary>
        /// <param name="src">要保存的文件的路径,如果保存文件到共享文件夹,这个路径就是本地文件路径如:@"D:\1.avi"</param>
        /// <param name="dst">保存文件的路径,不含名称及扩展名</param>
        /// <param name="fileName">保存文件的名称以及扩展名</param>
        public static void Transport(string src, string dst, string fileName)
        {

            FileStream inFileStream = new FileStream(src, FileMode.Open);
            if (!Directory.Exists(dst))
            {
                Directory.CreateDirectory(dst);
            }
            dst = dst + fileName;

            if (!File.Exists(dst))
            {
                FileStream outFileStream = new FileStream(dst, FileMode.Create, FileAccess.Write);


                byte[] buf = new byte[inFileStream.Length];

                int byteCount;

                while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
                {

                    outFileStream.Write(buf, 0, byteCount);

                }

                inFileStream.Flush();

                inFileStream.Close();

                outFileStream.Flush();

                outFileStream.Close();
            }
        }

        /// <summary>
        /// 从远程服务器下载文件到本地
        /// </summary>
        /// <param name="src">下载到本地后的文件路径,包含文件的扩展名</param>
        /// <param name="dst">远程服务器路径(共享文件夹路径)</param>
        /// <param name="fileName">远程服务器(共享文件夹)中的文件名称,包含扩展名</param>
        public static void TransportRemoteToLocal(string src, string dst, string fileName)   //src:下载到本地后的文件路径  dst:远程服务器路径 fileName:远程服务器dst路径下的文件名
        {
            if (!Directory.Exists(dst))
            {
                Directory.CreateDirectory(dst);
            }
            dst = dst + fileName;
            if (File.Exists(dst))
            {
                FileStream inFileStream = new FileStream(dst, FileMode.Open);    //远程服务器文件  此处假定远程服务器共享文件夹下确实包含本文件,否则程序报错

                FileStream outFileStream = new FileStream(src, FileMode.OpenOrCreate);   //从远程服务器下载到本地的文件

                byte[] buf = new byte[inFileStream.Length];

                int byteCount;

                while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
                {

                    outFileStream.Write(buf, 0, byteCount);

                }
                inFileStream.Flush();

                inFileStream.Close();

                outFileStream.Flush();

                outFileStream.Close();
            }
        }

        /// <summary>
        /// 检查是否能正常连接FTP服务器
        /// </summary>
        /// _ftpServerIP   IP +端口号
        /// _ftpUserID 用户名,_ftpPassword 密码
        /// <returns></returns>
        public static bool CheckFtp(string _ftpServerIP, string _ftpUserID, string _ftpPassword)
        {
            try
            {
                FtpWebRequest ftprequest = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + _ftpServerIP + "/"));
                ftprequest.Credentials = new NetworkCredential(_ftpUserID, _ftpPassword);
                ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;
                ftprequest.Timeout = 600000;
                FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();
                ftpResponse.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// FTP下载方法
        /// </summary>
        /// <param name="filePath">下载文件存储路径</param>
        /// <param name="fileName">下载文件名称</param>
        public static bool Download(string ftp, string UserName, string Password, string filePath, string fileName)
        {
            FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(ftp));
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(UserName, Password);
            try
            {
                FileStream outputStream = new FileStream(filePath + fileName, FileMode.Create);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftp + fileName));
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(UserName, Password);
                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();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }


        
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值