c#创建windows服务并定时发送文件到java服务器

创建c#windows服务是参照https://blog.csdn.net/xgf415/article/details/53786431文档做的,启发很大

创建定时是参照https://www.cnblogs.com/goto/p/4172274.html文档做的

最终合并代码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.ServiceProcess;
using System.Text;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        System.Timers.Timer timer1;  //计时器
                                     //自定义一个类
        public class FileTimeInfo
        {
            public string FileName;  //文件名
            public DateTime FileCreateTime; //创建时间
        }
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer1 = new System.Timers.Timer();

            timer1.Interval = 3000;  //设置计时器事件间隔执行时间

            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);

            timer1.Enabled = true;
        }

        protected override void OnStop()
        {
            this.timer1.Enabled = false;
        }
        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)

        {

            //使用 GetLatestFileTimeInfo
            //获取d:\test文件中,扩展名为.pdf的最新文件
            FileTimeInfo fi = GetLatestFileTimeInfo(@"d:\test", ".pdf");
            if (fi != null)
            {
                Console.WriteLine("文件名:{0} 创建时间:{1}", fi.FileName, fi.FileCreateTime);
                //Console.WriteLine(Path.GetFileName(fi.FileName));
            }
            else
            {
                Console.WriteLine("文件夹中没有指定扩展名的文件!");
            }
            StartSend(fi.FileName, Path.GetFileName(fi.FileName));
            //String file = @"d://test//test1.pdf";
            //创建PdfDocument实例
            /**
            PdfDocument pdf = new PdfDocument();
            //加载PDF文档  
            pdf.LoadFromFile(fi.FileName);

            //获取第一页  
            PdfPageBase page = pdf.Pages[0];

            //从第一页的指定矩形区域内提取文本  
            string text = page.ExtractText(new RectangleF(50, 50, 500, 100));

            //保存文本到.txt文件  
            StringBuilder sb = new StringBuilder();
            sb.AppendLine(text);
            File.WriteAllText(@"d://Extract233.txt", sb.ToString());
       **/

        }
        //获取最近创建的文件名和创建时间
        //如果没有指定类型的文件,返回null
        static FileTimeInfo GetLatestFileTimeInfo(string dir, string ext)
        {
            List<FileTimeInfo> list = new List<FileTimeInfo>();
            DirectoryInfo d = new DirectoryInfo(dir);
            foreach (FileInfo fi in d.GetFiles())
            {
                if (fi.Extension.ToUpper() == ext.ToUpper())
                {
                    list.Add(new FileTimeInfo()
                    {
                        FileName = fi.FullName,
                        FileCreateTime = fi.CreationTime
                    });
                }
            }
            var qry = from x in list
                      orderby x.FileCreateTime
                      select x;
            return qry.LastOrDefault();
        }
        static int StartSend(string path, string fileName)
        {
            if (!File.Exists(path))
            {
                return -1;
            }
            NetworkStream stream = null;
            BinaryWriter sw = null;
            FileStream fsMyfile = null;
            BinaryReader brMyfile = null;
            try
            {
                TcpClient client = new TcpClient("192.168.1.112", 8888);
                stream = client.GetStream();
                sw = new BinaryWriter(stream);
                ///取得文件名字节数组
                byte[] fileNameBytes = Encoding.Default.GetBytes(fileName);
                byte[] fileNameBytesArray = new byte[1024];
                Array.Copy(fileNameBytes, fileNameBytesArray, fileNameBytes.Length);
                ///写入流
                sw.Write(fileNameBytesArray, 0, fileNameBytesArray.Length);
                sw.Flush();
                ///获取文件内容字节数组
                ///byte[] fileBytes = returnbyte(filePath);
                fsMyfile = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                brMyfile = new BinaryReader(fsMyfile);
                ///写入流
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = brMyfile.Read(buffer, 0, 1024)) > 0)
                {
                    sw.Write(buffer, 0, count);
                    sw.Flush();
                    buffer = new byte[1024];
                }
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.StackTrace);
                return -2;
            }
            catch (IOException ioe)
            {
                Console.WriteLine(ioe.StackTrace);
                return -3;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                return -4;
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
                if (brMyfile != null)
                {
                    brMyfile.Close();
                }
                if (fsMyfile != null)
                {
                    fsMyfile.Close();
                }
                if (stream != null)
                {
                    stream.Close();
                }
            }
            return 0;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值