刚写的一个时时检测文件并上传到FTP的程序

本文介绍了一个基于C#实现的Ftp文件上传程序,能够检测本地文件是否存在,并检查Ftp服务器上的文件是否已存在及文件大小是否一致,不一致时进行替换。文章详细展示了程序代码,包括读取配置文件、上传文件、定时检测等功能。
这个程序主要实现了Ftp上传功能,检测本地文件是否存在,存在则查询Ftp上是否存在该文件,存在则继续查询文件的大小,当两个大小不符合的时候替换掉原有的程序,当然这不是最好的方法,有更好的可以在评论里提示下大笑,下面我来展示下我的代码:

 private ManualResetEvent wait;
        private FtpWebRequest request;
        private string fileName;
        private Exception operationException = null;
        string status;

        public FtpState()
        {
            wait = new ManualResetEvent(false);
        }

        public ManualResetEvent OperationComplete
        {
            get { return wait; }
        }

        public FtpWebRequest Request
        {
            get { return request; }
            set { request = value; }
        }

        public string FileName
        {
            get { return fileName; }
            set { fileName = value; }
        }
        public Exception OperationException
        {
            get { return operationException; }
            set { operationException = value; }
        }
        public string StatusDescription
        {
            get { return status; }
            set { status = value; }
        }
    }
    public class Program
    {
        //文件名
        public static string Filename = "";
        //本地文件路径
        public static string filepath = "";
        //ftp路径
        public static string ftppath = "";
        //输出信息
        private string message = "";
        private static bool complete;
        private static Timer tmr;
        public static Program obj = new Program();
        public static Thread t;
        //Ftp账号
        public static string uname = "";
        //Ftp密码
        public static string upwd = "";
        //本地文件大小
        public static long filesize;
        public static void Main(string[] args)
        {
            //读取xml文件,这边主要是获取配置
            XmlTextReader xtr = new XmlTextReader("UplaodInfo.xml");
            XmlDocument xd = new XmlDocument();
            xd.Load(xtr);
            ftppath = xd.SelectSingleNode("ftp").SelectSingleNode("ftpurl").InnerText;
            uname = xd.SelectSingleNode("ftp").SelectSingleNode("uname").InnerText;
            upwd = xd.SelectSingleNode("ftp").SelectSingleNode("upwd").InnerText;
            filepath = xd.SelectSingleNode("ftp").SelectSingleNode("fileurl").InnerText;
            Filename = xd.SelectSingleNode("ftp").SelectSingleNode("filename").InnerText;
            xtr.Close();
            obj = new Program();
            t = new Thread(new ThreadStart(obj.GenerateText));
            t.Start();
            Console.ReadLine();
        }

        public string UploadFile()//上传
        {
            try
            {
                tmr.Change(-1, -1);
                if (!GetFileList())
                {

                    ManualResetEvent waitObject;
                    string fname = Filename;
                    string item = ftppath + "/" + Filename;
                    Uri target = new Uri(item);
                    string fileName = filepath + "/" + Filename;
                    FtpState state = new FtpState();
                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
                    request.Method = WebRequestMethods.Ftp.UploadFile;

                    request.Credentials = new NetworkCredential(uname, upwd);
                    state.Request = request;
                    state.FileName = fileName;
                    waitObject = state.OperationComplete;
                    request.BeginGetRequestStream(
                        new AsyncCallback(EndGetStreamCallback),
                        state
                    );

                    waitObject.WaitOne();

                    if (state.OperationException != null)
                    {
                        return "上传失败!";
                        throw state.OperationException;
                    }
                    else
                    {
                        return "上传成功!";
                    }
                }


                else
                {
                    return "FTP上文件已存在!";
                }
            }
            catch (Exception)
            {

                return "上传失败!";
            }
            //return "";
        }

        public void GenerateText()//时时检测
        {
            TimerCallback tmrCallBack = new TimerCallback(obj.GetText);
            tmr = new Timer(tmrCallBack, null, TimeSpan.Zero, TimeSpan.FromMinutes(0.1));

            do
            {
                if (complete)
                {
                    break;
                }
            } while (true);
        }
        private static void EndGetStreamCallback(IAsyncResult ar)
        {
            //开始上传
            FtpState state = (FtpState)ar.AsyncState;

            Stream requestStream = null;
            // End the asynchronous call to get the request stream.
            try
            {

                requestStream = state.Request.EndGetRequestStream(ar);
                // Copy the file contents to the request stream.
                const int bufferLength = 2048;
                byte[] buffer = new byte[bufferLength];
                int count = 0;
                int readBytes = 0;
                FileStream stream = File.OpenRead(state.FileName);
                do
                {
                    readBytes = stream.Read(buffer, 0, bufferLength);
                    requestStream.Write(buffer, 0, readBytes);
                    count += readBytes;
                }
                while (readBytes != 0);
                //Console.WriteLine("Writing {0} bytes to the stream.", count);
                // IMPORTANT: Close the request stream before sending the request.
                requestStream.Close();
                // Asynchronously get the response to the upload request.
                state.Request.BeginGetResponse(
                    new AsyncCallback(EndGetResponseCallback),
                    state
                );
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                // Console.WriteLine("Could not get the request stream.");
                state.OperationException = e;
                state.OperationComplete.Set();
                return;
            }

        }

        // The EndGetResponseCallback method  
        // completes a call to BeginGetResponse.
        private static void EndGetResponseCallback(IAsyncResult ar)
        {
            //上传结束
            FtpState state = (FtpState)ar.AsyncState;
            FtpWebResponse response = null;
            try
            {
                response = (FtpWebResponse)state.Request.EndGetResponse(ar);
                response.Close();
                state.StatusDescription = response.StatusDescription;
                // Signal the main application thread that 
                // the operation is complete.
                state.OperationComplete.Set();
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                //Console.WriteLine("Error getting response.");
                state.OperationException = e;
                state.OperationComplete.Set();
            }
        }

        public static bool GetFileList()//从ftp服务器上获得文件列表
        {
            Uri target = new Uri(ftppath);
            FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(target);
            ftp.UseBinary = true;
            ftp.Credentials = new NetworkCredential(uname, upwd);
            try
            {

                ftp.Method = WebRequestMethods.Ftp.ListDirectory;
                WebResponse response = ftp.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名
                string line = reader.ReadLine();
                while (line != null)
                {
                    if (line == Filename)
                    {
                        reader.Close();
                        Uri sizetarget = new Uri(ftppath+"/"+Filename);
                        FtpWebRequest sizeftp = (FtpWebRequest)WebRequest.Create(sizetarget);
                        sizeftp.UseBinary = true;
                        sizeftp.Credentials = new NetworkCredential(uname, upwd);
                        sizeftp.Method = WebRequestMethods.Ftp.GetFileSize;
                        WebResponse sizeresponse = sizeftp.GetResponse();
                        long sizeline = sizeresponse.ContentLength;
                        if (sizeline == filesize)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }

                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                return false;
            }
            return false;
        }

        public void GetText(object state)//获取本地文件并执行上传
        {
            StringBuilder sb = new StringBuilder();
            if (!File.Exists(filepath + "/" + Filename))
            {
                sb.Append("-----------------本地文件不存在!-----------------");
                Console.ForegroundColor = ConsoleColor.Red;
            }
            else
            {
                FileInfo file = new FileInfo(filepath + "/" + Filename);
                filesize = file.Length;
                sb.Append("找到文件!");
                string Msg = UploadFile();
                sb.Append(Msg);
                if (Msg == "上传成功!")
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                }
                else if (Msg == "FTP上文件已存在!")
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                }
            }
            tmr.Change(TimeSpan.FromMinutes(0.1), TimeSpan.FromMinutes(0.1));
            sb.Append(Environment.NewLine);
            message = sb.ToString();
            Console.WriteLine("上传信息: ");
            Console.WriteLine(message);
            complete = true;
        }


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值