메뉴 건너뛰기

라이온하트 2nd edition

홈페이지를 새롭게 리뉴얼합니다.

C#
2013.11.04 06:23

FTP upload 기능 구현

조회 수 248418 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
using System;
using System.Net;
using System.Threading;

using System.IO;
namespace Examples.System.Net
{
    public class FtpState
    {
        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 AsynchronousFtpUpLoader
    {  
        // Command line arguments are two strings:
        // 1. The url that is the name of the file being uploaded to the server.
        // 2. The name of the file on the local machine.
        //
        public static void Main(string[] args)
        {
            // Create a Uri instance with the specified URI string.
            // If the URI is not correctly formed, the Uri constructor
            // will throw an exception.
            ManualResetEvent waitObject;
            
            Uri target = new Uri (args[0]);
            string fileName = args[1];
            FtpState state = new FtpState();
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            
            // This example uses anonymous logon.
            // The request is anonymous by default; the credential does not have to be specified. 
            // The example specifies the credential only to
            // control how actions are logged on the server.
            
            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
            
            // Store the request in the object that we pass into the
            // asynchronous operations.
            state.Request = request;
            state.FileName = fileName;
            
            // Get the event to wait on.
            waitObject = state.OperationComplete;
            
            // Asynchronously get the stream for the file contents.
            request.BeginGetRequestStream(
                new AsyncCallback (EndGetStreamCallback), 
                state
            );
            
            // Block the current thread until all operations are complete.
            waitObject.WaitOne();
            
            // The operations either completed or threw an exception.
            if (state.OperationException != null)
            {
                throw state.OperationException;
            }
            else
            {
                Console.WriteLine("The operation completed - {0}", state.StatusDescription);
            }
        }
        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();
            }
        }
    }
}


[출처] C# - FTP 서버에 파일을 업로드하는 방법 (THE WORLD OF CODE) |작성자 자바프로
URL: http://cafe.naver.com/issu3/249


List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
65 OS [CentOS] NTFS마운트하기 LionHeart 2014.08.22 74557
64 OS CentOS 6.x 설치 시 BIOS RAID metadata 문제 LionHeart 2014.08.22 113509
63 Information XE 속도개선 (XE 캐시파일 초기화 시간 줄이는 팁) - 다국어 제거 file LionHeart 2014.08.22 70579
62 OS Chrome on Centos LionHeart 2014.08.21 92883
61 OS INSTALLING NVIDIA LINUX DRIVERS IN A XEN ENABLED KERNEL LionHeart 2014.08.21 189915
60 OS Install NVIDIA Drivers in XEN Kernel LionHeart 2014.08.21 132839
59 Information XE 속도 개선팁 모음 1 LionHeart 2014.08.21 93796
58 OS memcached 설치 및 설정 LionHeart 2014.08.16 109541
57 Computer XE 쇼핑몰 솔루션 LionHeart 2014.08.12 64132
56 Computer 알아두면 유용한 무료사이트 20선 1 LionHeart 2014.08.06 90142
55 OS Ubuntu, HWP 2008 installation on x86 and x64 (only Link) 1 LionHeart 2014.07.23 112368
54 OS USB 저장장치에 의한 데이터 유출 방지 방법 1 LionHeart 2014.07.22 213680
53 C# 파일검색 루틴 (개발용) 2 LionHeart 2014.07.21 113159
52 OS Realtek 8723be-bt 무선랜 드라이버 (한성 u44x ) LionHeart 2014.07.18 161420
51 OS [LINK] 윈도우 8 관리자 권한 설정으로 항상 관리자 권한 얻기 LionHeart 2014.06.30 125324
50 C# C# How to make a simple MP3 player in C# LionHeart 2014.06.25 139625
49 Android [ 유니티3D엔진 ] FPS 프레임 조절 badung007 2014.06.15 129098
48 OS [ OS X ] 폴더 숨김파일 표시 badung007 2014.06.14 80017
47 C# C#에서 무료 TTS 사용하기 LionHeart 2014.06.09 131828
46 OS 우분투 sudo 비밀번호 안물어보게 하기 LionHeart 2014.06.03 102827
Board Pagination ‹ Prev 1 ... 3 4 5 6 7 8 9 10 11 12 Next ›
/ 12