Пример #1
0
        static void UploadToFTP(string FileToUpload)
        {
            FileInfo      FileInformation = new FileInfo(FileToUpload);
            string        FTPUri          = "ftp://localhost/" + FileInformation.Name;
            FtpWebRequest FTPRequest;

            //Create FtpWebRequest object and passing Creditails
            FTPRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://localhost/" + FileInformation.Name));
            //FTPRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            FTPRequest.Credentials = new NetworkCredential();

            //Close request after command is executed
            FTPRequest.KeepAlive = false;

            //Specify the command to be executed and mode
            FTPRequest.Method    = WebRequestMethods.Ftp.UploadFile;
            FTPRequest.UseBinary = true;

            //File size notification
            FTPRequest.ContentLength = FileInformation.Length;

            int buffLength = 2048; //2kb

            byte[] buff = new byte[buffLength];
            int    contentLen;

            //Open the file stream
            FileStream FTPFs = FileInformation.OpenRead();

            try
            {
                // Stream to which the file to be upload is written
                Stream StreamRequest = FTPRequest.GetRequestStream();

                // Read from the file stream 2kb at a time
                contentLen = FTPFs.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the
                    // FTP Upload Stream
                    StreamRequest.Write(buff, 0, contentLen);
                    contentLen = FTPFs.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                StreamRequest.Close();
                FTPFs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("Press any key to contine...");
                Console.Read();
            }
        }