본문 바로가기
다물칸 주소복사
조회 수 163 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

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

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
Extra Form
구분 팁&트릭
출처 내가작성

단일 파일을 업로드하는 함수 입니다. 복수파일 업로드는 이걸 응용하면 되겠지욤!!


public void UploadFile(string localFile, string RemoteFolder, string RemoteFileName = "")
        {
            string host = Properties.Settings.Default.FTPIP;

            if (Properties.Settings.Default.FTPPort == "")
            {
                Properties.Settings.Default.FTPPort = "22";
                Properties.Settings.Default.Save();
            }

            int port = Convert.ToInt32(Properties.Settings.Default.FTPPort);
            string userName = Properties.Settings.Default.FTPID;
            string userPwd = Properties.Settings.Default.FTPPwd;


            SshClient sshClient = new SshClient(host, port, userName, userPwd);

            sshClient.Connect();

            if (sshClient.IsConnected)
            {
                SftpClient ftpClient = new SftpClient(sshClient.ConnectionInfo);
                ftpClient.Connect();

                // 경로의 구분자 "/"로 For~Loop를 돌리자
                string[] sRemoteFolder = RemoteFolder.Split('/');

                for (int i = 0; i < sRemoteFolder.Count(); i++ )
                {
                    FTPCreateFolder(ftpClient, sRemoteFolder[i]);
                    ftpClient.ChangeDirectory(sRemoteFolder[i]);
                }

                Stream sourceStream = File.OpenRead(localFile);

                string curFolder = ftpClient.WorkingDirectory;
                string sFileName = string.Empty;

                if (RemoteFileName == "")
                {
                    sFileName = ProcGetFileName2(localFile);
                }
                else
                {
                    sFileName = RemoteFileName;
                }
                

                ftpClient.UploadFile(sourceStream, sFileName);

                //Close connections / file streams
                sshClient.Disconnect();
                ftpClient.Disconnect();
                ftpClient.Dispose();
                sshClient.Dispose();
            }
        }

        /// <summary>
        /// 경로나 파일에서 확장자를 포함한 파일명을 가져오는 함수
        /// </summary>
        /// <param name="strPath"></param>
        /// <returns></returns>
        private string ProcGetFileName2(string strPath)
        {
            string strRet = "";


            if (strPath == "")
                return strRet;

            strRet = Path.GetFileName(strPath);
            return strRet;
        }

        private void FTPCreateFolder(SftpClient ftpclient, string folderPath)
        {
            if (!ftpclient.IsConnected)
                return;

            try
            {
                ftpclient.CreateDirectory(folderPath);
            }
            catch
            {

            }
        }