简体   繁体   中英

How do i upload text file to my ftp every minute?

I have ftp server and i want to upload to the ftp using a timer every minute the same text file. For the test im using this method:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;

namespace ScrollLabelTest
{
    class FtpFileUploader
    {
        static string ftpurl = "ftp://ftp.test.com/";
        static string filename = @"c:\temp\test.txt";
        static string ftpusername = "name";
        static string ftppassword = "pass";
        static string value;

        public static void test()
        {
            try
            {
                FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(ftpurl + "" + ftpusername + "_" + filename);
                ftpClient.Credentials = new System.Net.NetworkCredential(ftpusername, ftppassword);
                ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
                ftpClient.UseBinary = true;
                ftpClient.KeepAlive = true;
                System.IO.FileInfo fi = new System.IO.FileInfo(filename);
                ftpClient.ContentLength = fi.Length;
                byte[] buffer = new byte[4097];
                int bytes = 0;
                int total_bytes = (int)fi.Length;
                System.IO.FileStream fs = fi.OpenRead();
                System.IO.Stream rs = ftpClient.GetRequestStream();
                while (total_bytes > 0)
                {
                    bytes = fs.Read(buffer, 0, buffer.Length);
                    rs.Write(buffer, 0, bytes);
                    total_bytes = total_bytes - bytes;
                }
                //fs.Flush();
                fs.Close();
                rs.Close();
                FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
                value = uploadResponse.StatusDescription;
                uploadResponse.Close();
            }
            catch(Exception err)
            {
                string t = err.ToString();
            }
        }
    }
}

I'm getting exception on the line:

FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(ftpurl + "" + ftpusername + "_" + filename);

The exception:

Invalid URI: Invalid port specified.

Try This:

FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpurl + 
                                            ftpusername + "_" + filename));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM