Beispiel #1
0
        public static void FtpUpload(string ftpPath, string user, string pwd, string inputFile)
        {
            //string ftpPath = "ftp://ftp.test.com/home/myindex.txt";
            //string user = "******";
            //string pwd = "ftppwd";
            //string inputFile = "index.txt";

            // WebRequest.Create로 Http,Ftp,File Request 객체를 모두 생성할 수 있다.
            System.Net.FtpWebRequest req = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(ftpPath);
            // FTP 업로드한다는 것을 표시
            req.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            // 쓰기 권한이 있는 FTP 사용자 로그인 지정
            req.Credentials = new System.Net.NetworkCredential(user, pwd);

            // 입력파일을 바이트 배열로 읽음
            byte[] data;
            using (StreamReader reader = new StreamReader(inputFile))
            {
                data = Encoding.UTF8.GetBytes(reader.ReadToEnd());
            }

            // RequestStream에 데이타를 쓴다
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
            }

            // FTP Upload 실행
            using (System.Net.FtpWebResponse resp = (System.Net.FtpWebResponse)req.GetResponse())
            {
                // FTP 결과 상태 출력
                Console.WriteLine("Upload: {0}", resp.StatusDescription);
            }
        }
Beispiel #2
0
        private T HandleListExceptions <T>(Func <T> func, System.Net.FtpWebRequest req)
        {
            T ret = default(T);

            HandleListExceptions(() => ret = func(), req);
            return(ret);
        }
Beispiel #3
0
        public static string SaveUploadedFileToFtp(ColumnField field, string strFileName, string contentType, System.IO.Stream stream)
        {
            if (!field.FtpUpload.Override && CheckIfFileExistInFtp(field, strFileName))
            {
                throw new DuradosException(field.View.Database.Localizer.Translate("File with same name already exist"));
            }


            System.Net.FtpWebRequest request = CreateFtpRequest(field, strFileName);

            request.Method = System.Net.WebRequestMethods.Ftp.UploadFile;

            byte[] buffer = new byte[stream.Length];

            //StreamReader sourceStream = new StreamReader(stream); //Only for text files !!!
            //byte[] fileContents = System.Text.Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());//Only for text files !!!

            int count = stream.Read(buffer, 0, buffer.Length);

            request.ContentLength = buffer.Length;

            using (Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(buffer, 0, buffer.Length);
            }

            System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse();

            response.Close();

            return(string.Empty);//response.StatusCode / response.StatusDescription
        }
Beispiel #4
0
        //http://stackoverflow.com/questions/12519290/downloading-files-using-ftpwebrequest
        public void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath)
        {
            int bytesRead = 0;

            byte[] buffer = new byte[2048];

            System.Net.FtpWebRequest request = CreateFtpWebRequest(ftpSourceFilePath, userName, password, true);
            request.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;

            System.IO.Stream reader = request.GetResponse().GetResponseStream();
            if (System.IO.File.Exists(localDestinationFilePath))
            {
                System.IO.File.Delete(localDestinationFilePath);
            }
            System.IO.FileStream fileStream = new System.IO.FileStream(localDestinationFilePath, System.IO.FileMode.Create);

            while (true)
            {
                bytesRead = reader.Read(buffer, 0, buffer.Length);

                if (bytesRead == 0)
                {
                    break;
                }

                fileStream.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();
        }
Beispiel #5
0
        public static List <string> FtpList(string ftpUrl, string ftpPath, string ftpUsername, string ftpPassword, bool usePassive = false, string searchRegEx = ".*")
        {
            System.Net.FtpWebRequest request = FtpRequest(
                ftpUrl: ftpUrl,
                ftpPath: ftpPath,
                ftpUsername: ftpUsername,
                ftpPassword: ftpPassword,
                ftpMethod: System.Net.WebRequestMethods.Ftp.ListDirectory,
                usePassive: usePassive
                );

            using (System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        List <string> lst_strFiles = new List <string>();
                        while (!reader.EndOfStream)
                        {
                            var line = reader.ReadLine();
                            if (Regex.Match(line, searchRegEx).Success)
                            {
                                lst_strFiles.Add(line);
                            }
                        }
                        return(lst_strFiles);
                    }
                }
            }
        }
Beispiel #6
0
        private System.Net.FtpWebRequest CreateRequest(string remotename, bool createFolder)
        {
            string url = m_url;

            if (createFolder && url.EndsWith("/"))
            {
                url = url.Substring(0, url.Length - 1);
            }

            System.Net.FtpWebRequest req = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(url + remotename);

            if (m_userInfo != null)
            {
                req.Credentials = m_userInfo;
            }
            req.KeepAlive = false;

            if (!m_defaultPassive)
            {
                req.UsePassive = m_passive;
            }

            if (m_useSSL)
            {
                req.EnableSsl = m_useSSL;
            }

            return(req);
        }
Beispiel #7
0
        public static System.Net.FtpWebResponse FtpDownload(string localFilePath, string ftpUrl, string ftpPath, string ftpUsername, string ftpPassword, bool usePassive = false)
        {
            System.Net.FtpWebRequest request = FtpRequest(
                ftpUrl: ftpUrl,
                ftpPath: ftpPath,
                ftpUsername: ftpUsername,
                ftpPassword: ftpPassword,
                ftpMethod: System.Net.WebRequestMethods.Ftp.DownloadFile,
                usePassive: usePassive
                );

            using (System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        using (StreamWriter destination = new StreamWriter(localFilePath))
                        {
                            destination.Write(reader.ReadToEnd());
                            destination.Flush();
                        }
                    }
                }
                return(response);
            }
        }
Beispiel #8
0
        public static System.Net.FtpWebResponse FtpUpload(string localFilePath, string ftpUrl, string ftpPath, string ftpUsername, string ftpPassword, bool usePassive = false)
        {
            // aggiunge il nome del file
            ftpPath = System.IO.Path.Combine(ftpPath, System.IO.Path.GetFileName(localFilePath));

            System.Net.FtpWebRequest request = FtpRequest(
                ftpUrl: ftpUrl,
                ftpPath: ftpPath,
                ftpUsername: ftpUsername,
                ftpPassword: ftpPassword,
                ftpMethod: System.Net.WebRequestMethods.Ftp.UploadFile,
                usePassive: usePassive
                );
            byte[] fileContents;
            using (System.IO.StreamReader sourceStream = new System.IO.StreamReader(localFilePath))
            {
                fileContents = System.Text.Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
            }
            request.ContentLength = fileContents.Length;
            using (System.IO.Stream requestStream = request.GetRequestStream())
            {
                requestStream.Write(fileContents, 0, fileContents.Length);
            }

            return((System.Net.FtpWebResponse)request.GetResponse());
        }
Beispiel #9
0
        static void UploadFile(string _FileName, string _UploadPath, string _FTPUser, string _FTPPass)
        {
            System.IO.FileInfo       _FileInfo      = new System.IO.FileInfo(_FileName);
            System.Net.FtpWebRequest _FtpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(_UploadPath));
            _FtpWebRequest.Credentials   = new System.Net.NetworkCredential(_FTPUser, _FTPPass);
            _FtpWebRequest.KeepAlive     = false;
            _FtpWebRequest.Timeout       = 20000;
            _FtpWebRequest.Method        = System.Net.WebRequestMethods.Ftp.UploadFile;
            _FtpWebRequest.UseBinary     = true;
            _FtpWebRequest.ContentLength = _FileInfo.Length;
            int buffLength = 2048;

            byte[] buff = new byte[buffLength];
            System.IO.FileStream _FileStream = _FileInfo.OpenRead();

            try
            {
                System.IO.Stream _Stream = _FtpWebRequest.GetRequestStream();
                int contentLen           = _FileStream.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    _Stream.Write(buff, 0, contentLen);
                    contentLen = _FileStream.Read(buff, 0, buffLength);
                }
                _Stream.Close();
                _Stream.Dispose();
                _FileStream.Close();
                _FileStream.Dispose();
            }
            catch (Exception ex)
            {
                loguj("Błąd FTP: " + ex.Message.ToString());
            }
        }
        internal FtpWebRequest(System.Net.FtpWebRequest webRequest)
            : base(webRequest)
        {
            if (webRequest == null)
                throw new ArgumentNullException("webRequest");

            _webRequest = webRequest;
        }
Beispiel #11
0
 public void Delete(string remotename)
 {
     System.Net.FtpWebRequest req = CreateRequest(remotename);
     req.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
     Utility.AsyncHttpRequest areq = new Utility.AsyncHttpRequest(req);
     using (areq.GetResponse())
     { }
 }
Beispiel #12
0
        private bool Upload(FileInfo fi, string targetFilename)
        {
            //copy the file specified to target file: target file can be full path or just filename (uses current dir)

            string host = this.gbaseFtpField.Text.Trim();

            if (host.EndsWith("/") == false)
            {
                host = host + "/";
            }
            string URI = host + targetFilename;

            //perform copy
            System.Net.FtpWebRequest ftp = GetRequest(URI);

            //Set request to upload a file in binary
            ftp.Method    = System.Net.WebRequestMethods.Ftp.UploadFile;
            ftp.UseBinary = true;

            //Notify FTP of the expected size
            ftp.ContentLength = fi.Length;

            //create byte array to store: ensure at least 1 byte!
            const int BufferSize = 2048;

            byte[] content = new byte[BufferSize - 1];
            int    dataRead;

            //open file for reading
            using (FileStream fs = fi.OpenRead())
            {
                try
                {
                    //open request to send
                    using (Stream rs = ftp.GetRequestStream())
                    {
                        do
                        {
                            dataRead = fs.Read(content, 0, BufferSize);
                            rs.Write(content, 0, dataRead);
                        }while (!(dataRead < BufferSize));
                        rs.Close();
                    }
                }
                catch (Exception ex)
                {
                    EventLog.LogEvent(ex);
                }

                finally
                {
                    //ensure file closed
                    fs.Close();
                }
            }
            ftp = null;
            return(true);
        }
Beispiel #13
0
 public void CreateFolder()
 {
     System.Net.FtpWebRequest req = CreateRequest("", true);
     req.Method    = System.Net.WebRequestMethods.Ftp.MakeDirectory;
     req.KeepAlive = false;
     Utility.AsyncHttpRequest areq = new Utility.AsyncHttpRequest(req);
     using (areq.GetResponse())
     { }
 }
Beispiel #14
0
 private System.Net.FtpWebRequest GetRequest(string URI)
 {
     //create request
     System.Net.FtpWebRequest result = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(URI);
     //Set the login details
     result.Credentials = GetCredentials();
     //Do not keep alive (stateless mode)
     result.KeepAlive = false;
     return(result);
 }
        internal FtpWebRequest(System.Net.FtpWebRequest webRequest)
            : base(webRequest)
        {
            if (webRequest == null)
            {
                throw new ArgumentNullException("webRequest");
            }

            _webRequest = webRequest;
        }
Beispiel #16
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="downFile"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public Boolean download(string url, string downFile, string username, string password)
        {
            Boolean ret = true;

            try
            {
                //ダウンロードするファイルのURI
                Uri u = new Uri(url);

                //FtpWebRequestの作成
                System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)
                                                  System.Net.WebRequest.Create(u);
                //ログインユーザー名とパスワードを設定
                ftpReq.Credentials = new System.Net.NetworkCredential(username, password);
                //MethodにWebRequestMethods.Ftp.DownloadFile("RETR")を設定
                ftpReq.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
                //要求の完了後に接続を閉じる
                ftpReq.KeepAlive = false;
                //ASCIIモードで転送する
                ftpReq.UseBinary = true;
                //PASSIVEモードを無効にする
                ftpReq.UsePassive = false;

                //FtpWebResponseを取得
                System.Net.FtpWebResponse ftpRes =
                    (System.Net.FtpWebResponse)ftpReq.GetResponse();
                //ファイルをダウンロードするためのStreamを取得
                System.IO.Stream resStrm = ftpRes.GetResponseStream();
                //ダウンロードしたファイルを書き込むためのFileStreamを作成
                System.IO.FileStream fs = new System.IO.FileStream(
                    downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                //ダウンロードしたデータを書き込む
                byte[] buffer = new byte[1024];
                while (true)
                {
                    int readSize = resStrm.Read(buffer, 0, buffer.Length);
                    if (readSize == 0)
                    {
                        break;
                    }
                    fs.Write(buffer, 0, readSize);
                }
                fs.Close();
                resStrm.Close();

                //閉じる
                ftpRes.Close();
            }
            catch (Exception ex)
            {
                NCLogger.GetInstance().WriteExceptionLog(ex);
                ret = false;
            }
            return(ret);
        }
Beispiel #17
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="upFile"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public Boolean uploadFile(string url, string upFile, string username, string password)
        {
            Boolean ret = true;

            try
            {
                //アップロード先のURI
                Uri u = new Uri(url);

                //FtpWebRequestの作成
                System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)
                                                  System.Net.WebRequest.Create(u);
                //ログインユーザー名とパスワードを設定
                ftpReq.Credentials = new System.Net.NetworkCredential(username, password);
                //MethodにWebRequestMethods.Ftp.UploadFile("STOR")を設定
                ftpReq.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
                //要求の完了後に接続を閉じる
                ftpReq.KeepAlive = false;
                //ASCIIモードで転送する
                ftpReq.UseBinary = true;
                //PASVモードを無効にする
                ftpReq.UsePassive = false;

                //ファイルをアップロードするためのStreamを取得
                System.IO.Stream reqStrm = ftpReq.GetRequestStream();
                //アップロードするファイルを開く
                System.IO.FileStream fs = new System.IO.FileStream(
                    upFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                //アップロードStreamに書き込む
                byte[] buffer = new byte[1024];
                while (true)
                {
                    int readSize = fs.Read(buffer, 0, buffer.Length);
                    if (readSize == 0)
                    {
                        break;
                    }
                    reqStrm.Write(buffer, 0, readSize);
                }
                fs.Close();
                reqStrm.Close();

                //FtpWebResponseを取得
                System.Net.FtpWebResponse ftpRes =
                    (System.Net.FtpWebResponse)ftpReq.GetResponse();
                //閉じる
                ftpRes.Close();
            }
            catch (Exception ex)
            {
                ret = false;
            }
            return(ret);
        }
Beispiel #18
0
        public void Get(string remotename, System.IO.Stream output)
        {
            System.Net.FtpWebRequest req = CreateRequest(remotename);
            req.Method    = System.Net.WebRequestMethods.Ftp.DownloadFile;
            req.UseBinary = true;

            Utility.AsyncHttpRequest areq = new Utility.AsyncHttpRequest(req);
            using (System.Net.WebResponse resp = areq.GetResponse())
                using (System.IO.Stream rs = areq.GetResponseStream())
                    Utility.Utility.CopyStream(rs, output, false);
        }
Beispiel #19
0
        public void Put(string remotename, System.IO.Stream input)
        {
            System.Net.FtpWebRequest req = null;
            try
            {
                req           = CreateRequest(remotename);
                req.Method    = System.Net.WebRequestMethods.Ftp.UploadFile;
                req.UseBinary = true;

                long streamLen = -1;
                try { streamLen = input.Length; }
                catch {}

                Utility.AsyncHttpRequest areq = new Utility.AsyncHttpRequest(req);
                using (System.IO.Stream rs = areq.GetRequestStream())
                    Utility.Utility.CopyStream(input, rs, true);

                if (m_listVerify)
                {
                    List <IFileEntry> files = List(remotename);
                    StringBuilder     sb    = new StringBuilder();
                    foreach (IFileEntry fe in files)
                    {
                        if (fe.Name.Equals(remotename) || fe.Name.EndsWith("/" + remotename) || fe.Name.EndsWith("\\" + remotename))
                        {
                            if (fe.Size < 0 || streamLen < 0 || fe.Size == streamLen)
                            {
                                return;
                            }

                            throw new Exception(string.Format(Strings.FTPBackend.ListVerifySizeFailure, remotename, fe.Size, streamLen));
                        }
                        else
                        {
                            sb.AppendLine(fe.Name);
                        }
                    }

                    throw new Exception(string.Format(Strings.FTPBackend.ListVerifyFailure, remotename, sb.ToString()));
                }
            }
            catch (System.Net.WebException wex)
            {
                if (req != null && wex.Response as System.Net.FtpWebResponse != null && (wex.Response as System.Net.FtpWebResponse).StatusCode == System.Net.FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    throw new Interface.FolderMissingException(string.Format(Strings.FTPBackend.MissingFolderError, req.RequestUri.PathAndQuery, wex.Message), wex);
                }
                else
                {
                    throw;
                }
            }
        }
Beispiel #20
0
 public static System.Net.FtpWebRequest FtpRequest(string ftpUrl, string ftpPath, string ftpUsername, string ftpPassword, string ftpMethod, bool usePassive = false)
 {
     if (!string.IsNullOrEmpty(ftpPath))
     {
         ftpUrl = $"{ftpUrl}{ftpPath}";
     }
     System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(ftpUrl);
     request.UsePassive  = usePassive;
     request.UseBinary   = true;
     request.KeepAlive   = false;
     request.Method      = ftpMethod;
     request.Credentials = new System.Net.NetworkCredential(ftpUsername, ftpPassword);
     return(request);
 }
Beispiel #21
0
        public void InitializeFtpRequestTest()
        {
            string strfilepath   = string.Empty;            // TODO: Initialize to an appropriate value
            string serverIP      = string.Empty;            // TODO: Initialize to an appropriate value
            string directoryName = string.Empty;            // TODO: Initialize to an appropriate value
            string userName      = string.Empty;            // TODO: Initialize to an appropriate value
            string strPwd        = string.Empty;            // TODO: Initialize to an appropriate value

            System.Net.FtpWebRequest reqFTP         = null; // TODO: Initialize to an appropriate value
            System.Net.FtpWebRequest reqFTPExpected = null; // TODO: Initialize to an appropriate value
            PIS.Ground.Core.Utility.FtpUpLoader_Accessor.InitializeFtpRequest(strfilepath, serverIP, directoryName, userName, strPwd, out reqFTP);
            Assert.AreEqual(reqFTPExpected, reqFTP);
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
Beispiel #22
0
        private System.Net.FtpWebRequest CreateFtpWebRequest(string ftpDirectoryPath, string userName, string password, bool keepAlive = false)
        {
            System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(new Uri(ftpDirectoryPath));

            //Set proxy to null. Under current configuration if this option is not set then the proxy that is used will get an html response from the web content gateway (firewall monitoring system)
            request.Proxy = null;

            request.UsePassive = true;
            request.UseBinary  = true;
            request.KeepAlive  = keepAlive;

            request.Credentials = new System.Net.NetworkCredential(userName, password);

            return(request);
        }
Beispiel #23
0
        public async Task PutAsync(string remotename, System.IO.Stream input, CancellationToken cancelToken)
        {
            System.Net.FtpWebRequest req = null;
            try
            {
                req           = CreateRequest(remotename);
                req.Method    = System.Net.WebRequestMethods.Ftp.UploadFile;
                req.UseBinary = true;

                long streamLen = -1;
                try { streamLen = input.Length; }
                catch {}

                Utility.AsyncHttpRequest areq = new Utility.AsyncHttpRequest(req);
                using (System.IO.Stream rs = areq.GetRequestStream(streamLen))
                    await Utility.Utility.CopyStreamAsync(input, rs, true, cancelToken, m_copybuffer).ConfigureAwait(false);

                if (m_listVerify)
                {
                    IEnumerable <IFileEntry> files = List(remotename);
                    foreach (IFileEntry fe in files)
                    {
                        if (fe.Name.Equals(remotename) || fe.Name.EndsWith("/" + remotename, StringComparison.Ordinal) || fe.Name.EndsWith("\\" + remotename, StringComparison.Ordinal))
                        {
                            if (fe.Size < 0 || streamLen < 0 || fe.Size == streamLen)
                            {
                                return;
                            }

                            throw new Exception(Strings.FTPBackend.ListVerifySizeFailure(remotename, fe.Size, streamLen));
                        }
                    }

                    throw new Exception(Strings.FTPBackend.ListVerifyFailure(remotename, files.Select(n => n.Name)));
                }
            }
            catch (System.Net.WebException wex)
            {
                if (req != null && wex.Response as System.Net.FtpWebResponse != null && (wex.Response as System.Net.FtpWebResponse).StatusCode == System.Net.FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    throw new Interface.FolderMissingException(Strings.FTPBackend.MissingFolderError(req.RequestUri.PathAndQuery, wex.Message), wex);
                }
                else
                {
                    throw;
                }
            }
        }
Beispiel #24
0
        /// <summary>
        /// エラーファイルをサーバにアップロードする
        /// </summary>
        /// <param name="strErrLogPath"></param>
        private void ErrMsgUpload(string strErrLogPath)
        {
            try
            {
                string upFile = strErrLogPath;

                Uri u = new Uri("ftp://aaa" + Path.GetFileName(strErrLogPath));

                System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)
                                                  System.Net.WebRequest.Create(u);

                ftpReq.Credentials = new System.Net.NetworkCredential("aaaa", "aaaa");
                ftpReq.Method      = System.Net.WebRequestMethods.Ftp.UploadFile;
                ftpReq.KeepAlive   = false;
                ftpReq.UseBinary   = false;
                ftpReq.UsePassive  = false;

                System.IO.Stream reqStrm = ftpReq.GetRequestStream();

                using (System.IO.FileStream fs = new System.IO.FileStream(
                           upFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    byte[] buffer = new byte[1024];
                    while (true)
                    {
                        int readSize = fs.Read(buffer, 0, buffer.Length);
                        if (readSize == 0)
                        {
                            break;
                        }
                        reqStrm.Write(buffer, 0, readSize);
                    }
                    fs.Close();
                }
                reqStrm.Close();

                System.Net.FtpWebResponse ftpRes =
                    (System.Net.FtpWebResponse)ftpReq.GetResponse();

                Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription);

                ftpRes.Close();
            }
            catch (System.Exception)
            {
            }
        }
Beispiel #25
0
        public List <string> GetManifestFileList()
        {
            List <string> result = new List <string>();

            // Get the object used to communicate with the server.
            System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(System.Configuration.ConfigurationManager.AppSettings["ftp_site"] + "/m");
            request.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["ftp_user_id"], System.Configuration.ConfigurationManager.AppSettings["ftp_password"]);

            System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse();

            System.IO.Stream       responseStream = response.GetResponseStream();
            System.IO.StreamReader reader         = new System.IO.StreamReader(responseStream);


            string line = reader.ReadLine();

            while (!string.IsNullOrEmpty(line))
            {
                if (line.StartsWith("-"))
                {
                    int start_index = line.LastIndexOf(' ');
                    result.Add(line.Substring(start_index).Trim());
                }
                line = reader.ReadLine();
            }

            /*
             * drwxrwxrwx   1 user     group           0 Apr 12 11:10 .
             * drwxrwxrwx   1 user     group           0 Apr 12 11:10 ..
             * drwxrwxrwx   1 user     group           0 Apr 12 10:42 Epi_Info_7-1-5
             * -rw-rw-rw-   1 user     group       10193 Apr 12 11:10 release-7.1.5.txt
             *
             */


            // Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);



            reader.Close();
            response.Close();

            return(result);
        }
Beispiel #26
0
 private void HandleListExceptions(Action action, System.Net.FtpWebRequest req)
 {
     try
     {
         action();
     }
     catch (System.Net.WebException wex)
     {
         if (wex.Response as System.Net.FtpWebResponse != null && (wex.Response as System.Net.FtpWebResponse).StatusCode == System.Net.FtpStatusCode.ActionNotTakenFileUnavailable)
         {
             throw new Interface.FolderMissingException(Strings.FTPBackend.MissingFolderError(req.RequestUri.PathAndQuery, wex.Message), wex);
         }
         else
         {
             throw;
         }
     }
 }
Beispiel #27
0
        private static System.Net.FtpWebRequest CreateFtpRequest(ColumnField field, string strFileName)
        {
            FtpUpload uploader = field.FtpUpload;

            string target = GetFtpUploadTarget(field, strFileName);

            System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)System.Net.HttpWebRequest.Create(target);

            //request.Credentials = new System.Net.NetworkCredential(uploader.FtpUserName, uploader.FtpPassword);
            //request.Credentials = new System.Net.NetworkCredential(uploader.FtpUserName, uploader.GetDecryptedPassword(Map.GetConfigDatabase()));
            request.Credentials = GetFtpNetworkCredential(field);

            request.UsePassive = uploader.UsePassive;
            request.UseBinary  = true;
            request.KeepAlive  = false;

            return(request);
        }
Beispiel #28
0
 public static bool FtpDelete(string ftpUrl, string ftpPath, string ftpUsername, string ftpPassword, bool usePassive = false)
 {
     System.Net.FtpWebRequest request = FtpRequest(
         ftpUrl: ftpUrl,
         ftpPath: ftpPath,
         ftpUsername: ftpUsername,
         ftpPassword: ftpPassword,
         ftpMethod: System.Net.WebRequestMethods.Ftp.DeleteFile,
         usePassive: usePassive
         );
     try
     {
         using (System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse())
         {
             return(response.StatusCode == System.Net.FtpStatusCode.FileActionOK);
         }
     }
     catch (System.Net.WebException)
     {
         return(false);
     }
 }
Beispiel #29
0
        public List <IFileEntry> List(string filename)
        {
            System.Net.FtpWebRequest req = CreateRequest(filename);
            req.Method    = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;
            req.UseBinary = false;

            try
            {
                List <IFileEntry>        lst  = new List <IFileEntry>();
                Utility.AsyncHttpRequest areq = new Utility.AsyncHttpRequest(req);
                using (System.Net.WebResponse resp = areq.GetResponse())
                    using (System.IO.Stream rs = areq.GetResponseStream())
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(new StreamReadHelper(rs)))
                        {
                            string line;
                            while ((line = sr.ReadLine()) != null)
                            {
                                FileEntry f = ParseLine(line);
                                if (f != null)
                                {
                                    lst.Add(f);
                                }
                            }
                        }
                return(lst);
            }
            catch (System.Net.WebException wex)
            {
                if (wex.Response as System.Net.FtpWebResponse != null && (wex.Response as System.Net.FtpWebResponse).StatusCode == System.Net.FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    throw new Interface.FolderMissingException(string.Format(Strings.FTPBackend.MissingFolderError, req.RequestUri.PathAndQuery, wex.Message), wex);
                }
                else
                {
                    throw;
                }
            }
        }
Beispiel #30
0
        private static bool CheckIfFileExistInFtp(ColumnField field, string strFileName)
        {
            System.Net.FtpWebRequest request = CreateFtpRequest(field, strFileName);
            request.Method = System.Net.WebRequestMethods.Ftp.GetDateTimestamp;

            try
            {
                var response = (System.Net.FtpWebResponse)request.GetResponse();
            }
            catch (System.Net.WebException ex)
            {
                var response = (System.Net.FtpWebResponse)ex.Response;
                if (response.StatusCode == System.Net.FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    return(false);
                }
                else
                {
                    throw new DuradosException(response.StatusDescription);
                }
            }

            return(true);
        }
Beispiel #31
0
        public string GetTextFileContent(string file_name)
        {
            string result = null;

            // Get the object used to communicate with the server.
            System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(System.Configuration.ConfigurationManager.AppSettings["ftp_site"] + "/m/" + file_name);
            request.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["ftp_user_id"], System.Configuration.ConfigurationManager.AppSettings["ftp_password"]);

            System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse();

            System.IO.Stream       responseStream = response.GetResponseStream();
            System.IO.StreamReader reader         = new System.IO.StreamReader(responseStream);


            result = reader.ReadToEnd();

            reader.Close();
            response.Close();

            return(result);
        }