Esempio n. 1
0
        public byte[] DownloadFile(string source)
        {
            //Logger.Debug("Đọc các tập tin trên FTP:{0}", source);
            CTLError.WriteError(string.Format("Đọc các tập tin trên FTP:{0}", source), "");
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpRootPath + source);

            req.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
            req.Method      = WebRequestMethods.Ftp.DownloadFile;
            req.UseBinary   = true;
            try
            {
                FtpWebResponse response = (FtpWebResponse)req.GetResponse();
                using (Stream ftpStream = response.GetResponseStream())
                    using (var memoryStream = new MemoryStream())
                    {
                        StreamExtensions.CopyTo(ftpStream, memoryStream);
                        //ftpStream.CopyTo(memoryStream);
                        //CopyTo(ftpStream, memoryStream);
                        response.Close();
                        req.Abort();
                        return(memoryStream.ToArray());
                    }
            }
            catch (Exception e)
            {
                //Logger.Warn("Đã xảy ra lỗi khi đọc tệp!{0}", e.Message);
                req.Abort();
                return(null);
            }
        }
Esempio n. 2
0
        //public Stream CopyTo(Stream input, Stream output)
        //{
        //    byte[] buffer = new byte[16 * 1024]; // Fairly arbitrary size
        //    int bytesRead;

        //    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
        //    {
        //        output.Write(buffer, 0, bytesRead);
        //    }
        //    return out
        //}
        public bool DeleteFile(string source)
        {
            CTLError.WriteError(string.Format("Xóa các tập tin trên FTP:{0}", source), "");
            //Logger.Debug("Xóa các tập tin trên FTP:{0}", source);
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpRootPath + source);

            req.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
            req.Method      = WebRequestMethods.Ftp.DeleteFile;
            try
            {
                FtpWebResponse response = (FtpWebResponse)req.GetResponse();
                response.Close();
            }
            catch (Exception e)
            {
                //Logger.Warn("Đã xảy ra lỗi khi xóa tệp!{0}", e.Message);
                CTLError.WriteError(string.Format("Đã xảy ra lỗi khi xóa tệp!"), e.Message);
                req.Abort();
                return(false);
            }
            req.Abort();
            CTLError.WriteError(string.Format("Xóa thành công!"), "");
            //Logger.Debug("Xóa thành công!");
            return(true);
        }
        //在服务器上创建相应的文件路径
        public bool MkDir(string remotePath)
        {
            if (!CheckPath(remotePath))
            {
                return(true);
            }
            FtpWebRequest ftpWebRequest = (FtpWebRequest)WebRequest.Create(remotePath);

            ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);

            ftpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory;

            try
            {
                FtpWebResponse response = (FtpWebResponse)ftpWebRequest.GetResponse();

                response.Close();
            }
            catch (Exception e)
            {
                ftpWebRequest.Abort();
                return(false);
            }
            ftpWebRequest.Abort();

            return(true);
        }
Esempio n. 4
0
        public void TransFile(IAsyncResult ar)
        {
            FileInfo file = ar.AsyncState as FileInfo;

            try
            {
                _requestStream = _uploadRequest.EndGetRequestStream(ar);
                _fileStream    = File.OpenRead(file.FullName);
                byte[] buffer = new byte[1024];
                int    bytesRead;
                if (_currLength < file.Length)
                {
                    //设置Position
                    _fileStream.Seek(_currLength, SeekOrigin.Begin);
                    while (true)
                    {
                        if (_abort)
                        {
                            _uploadRequest.Abort();
                            break;
                        }
                        bytesRead = _fileStream.Read(buffer, 0, buffer.Length);
                        if (bytesRead == 0)
                        {
                            break;
                        }
                        _requestStream.Write(buffer, 0, bytesRead);
                        _currLength += bytesRead;
                    }
                }
                RomoveFile(file);

                //添加到已完成列表中
                if (!_abort)
                {
                    _uploadedFiles.Add(file);
                }

                if (!_abort)
                {
                    _uploadRequest.BeginGetResponse(new AsyncCallback(UploadNextFile), null);
                }
                else
                {
                    UploadFile(null);
                }
            }
            catch (Exception e)
            {
                _result = e.Message;
                RomoveFile(file);
                UploadFile(null);
            }
        }
        /// <summary>
        /// Determines whether this instance can connect to the FTP server. Run as little as possible, since it blocks the main thread while checking.
        /// </summary>
        /// <returns><c>true</c> if this instance can connect to the FTP server; otherwise, <c>false</c>.</returns>
        public bool CanConnectToFTP()
        {
            bool bCanConnectToFTP;

            string FTPURL      = Config.GetFTPUrl();
            string FTPUserName = Config.GetFTPUsername();
            string FTPPassword = Config.GetFTPPassword();

            try
            {
                FtpWebRequest plainRequest = (FtpWebRequest)FtpWebRequest.Create(FTPURL);
                plainRequest.Credentials = new NetworkCredential(FTPUserName, FTPPassword);
                plainRequest.Method      = WebRequestMethods.Ftp.ListDirectory;
                plainRequest.Timeout     = 8000;

                try
                {
                    WebResponse response = plainRequest.GetResponse();

                    plainRequest.Abort();
                    response.Close();

                    bCanConnectToFTP = true;
                }
                catch (WebException wex)
                {
                    Console.WriteLine("WebException in CanConnectToFTP(): " + wex.Message);
                    Console.WriteLine(FTPURL);

                    plainRequest.Abort();
                    bCanConnectToFTP = false;
                }
            }
            catch (WebException wex)
            {
                //case where FTP URL in config is not valid
                Console.WriteLine("WebException CanConnectToFTP() (Invalid URL): " + wex.Message);

                bCanConnectToFTP = false;
                return(bCanConnectToFTP);
            }

            if (!bCanConnectToFTP)
            {
                Console.WriteLine("Failed to connect to FTP server at: {0}", Config.GetFTPUrl());
                bCanConnectToFTP = false;
            }

            return(bCanConnectToFTP);
        }
        public bool Upload(string filePath, string localFile)
        {
            //检查目录是否存在,不存在创建
            FtpCheckDirectoryExist(filePath);

            FileInfo      fi     = new FileInfo(localFile);
            FileStream    fs     = fi.OpenRead();
            long          length = fs.Length;
            string        fd     = System.Web.HttpUtility.UrlEncode(fi.Name);
            FtpWebRequest req    = CreateFtpWebRequest(ftpUristring + filePath + fd, WebRequestMethods.Ftp.UploadFile);

            req.ContentLength = length;
            double startbye   = 0;
            int    contentLen = 0;

            req.Timeout = 10 * 1000;
            try
            {
                Stream stream       = req.GetRequestStream();
                int    BufferLength = 8196;
                byte[] b            = new byte[BufferLength];
                contentLen = fs.Read(b, 0, BufferLength);

                while (contentLen != 0)
                {
                    stream.Write(b, 0, contentLen);
                    contentLen = fs.Read(b, 0, BufferLength);
                    startbye  += contentLen;
                }
                stream.Close();
                stream.Dispose();
                FtpWebResponse response = GetFtpResponse(req);
                if (response == null)
                {
                    return(false);
                }
            }
            catch (Exception ee)
            {
                return(false);
            }
            finally
            {
                fs.Close();
                req.Abort();
            }
            req.Abort();

            return(true);
        }
Esempio n. 7
0
        /// <summary>
        /// 文件存在检查
        /// </summary>
        /// <param name="remoteFilePath">删除文件的FTP路径和名称(相对FTP根目录)</param>
        /// <param name="ftpServerIP">FTP服务器IP地址</param>
        /// <param name="loginName">FTP 服务器登录名</param>
        /// <param name="loginPassword">FTP 服务器登录密码</param>
        /// <returns></returns>
        public bool fileCheckExist(string remoteFilePath, string ftpServerIP, string loginName, string loginPassword)
        {
            string        uri    = "ftp://" + ftpServerIP + "/" + remoteFilePath;
            FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(uri));

            reqFTP.Credentials = new NetworkCredential(loginName, loginPassword);
            reqFTP.Method      = WebRequestMethods.Ftp.ListDirectory;
            reqFTP.KeepAlive   = false;

            string fileName = remoteFilePath.Substring(remoteFilePath.LastIndexOf('/') + 1);

            WebResponse  webResponse = null;
            StreamReader reader      = null;
            bool         success     = false;

            try
            {
                webResponse = reqFTP.GetResponse();
                reader      = new StreamReader(webResponse.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                    if (line == fileName)
                    {
                        success = true;
                        break;
                    }
                    line = reader.ReadLine();
                }
            }
            catch (Exception ex)
            {
                reqFTP.Abort();
                LogHelper.Error(typeof(FTPHelper), "FilePath:" + remoteFilePath, ex);
                success = false;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (webResponse != null)
                {
                    webResponse.Close();
                }
                reqFTP.Abort();
            }
            return(success);
        }
Esempio n. 8
0
        public static bool PutFileFTP(string server, string username, string password, string path, FileInfo fi)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + server + path + "/" + fi.Name);

                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive  = true;
                request.Method      = WebRequestMethods.Ftp.UploadFile;
                //request.EnableSsl = true; // если используется ssl

                byte[] file_to_bytes = new byte[fi.Length];
                using (FileStream uploadedFile = fi.OpenRead())
                    uploadedFile.Read(file_to_bytes, 0, file_to_bytes.Length);

                if (file_to_bytes?.Length > 0)
                {
                    using (Stream writer = request.GetRequestStream())
                        writer.Write(file_to_bytes, 0, file_to_bytes.Length);
                    return(true);
                }
                else
                {
                    request.Abort();
                }
            }
            catch
            {
            }
            return(false);
        }
Esempio n. 9
0
        public async void DownloadFileAsync(string fname, string dir) //Corrected
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url + @"/" + fname);

            request.Credentials = new NetworkCredential(login, password);
            request.Method      = WebRequestMethods.Ftp.DownloadFile;
            FtpWebResponse response;
            FileStream     writeStream;
            await Task.Run(
                () =>
            {
                try
                {
                    response              = (FtpWebResponse)request.GetResponse();
                    writeStream           = new FileStream(dir + fname.Substring(fname.LastIndexOf(@"\")), FileMode.Create);
                    Stream responseStream = request.GetResponse().GetResponseStream();
                    //int len = GetStreamLength(responseStream);
                    //byte[] bytes = new byte[len];
                    //responseStream.Read(bytes, 0, bytes.Length);
                    byte[] bytes = GetBytesFromStream(responseStream);
                    writeStream.Write(bytes, 0, bytes.Length);
                    writeStream.Close();
                    responseStream.Close();
                    onUploadEnded?.Invoke(this, response.StatusDescription);
                    request.Abort();
                }
                catch (Exception e)
                {
                    onError?.Invoke(this, e);
                }
            });
        }
Esempio n. 10
0
        public void DownloadAllRelated(string baseFTPpath, string filePath, string related, ProgressBar pb)
        {
            string[]      allFile    = ListAllFiles();
            List <string> relateFile = getSpecFileList(allFile, related);

            foreach (var item in relateFile)
            {
                string tempURL = baseFTPpath + item;
                try
                {
                    request             = (FtpWebRequest)WebRequest.Create(tempURL);
                    request.Credentials = new NetworkCredential(Username, Password);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
                finally
                {
                    if (request != null)
                    {
                        request.Abort();
                    }
                }
                URL = tempURL;
                DownFile(filePath, pb);
            }
        }
Esempio n. 11
0
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="directory">文件夹</param>
        public void MakeDirectory(string directory)
        {
            FtpWebRequest  request  = null;
            FtpWebResponse response = null;

            try
            {
                request             = FtpWebRequest.Create(ftpSite + directory) as FtpWebRequest;
                request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
                request.KeepAlive   = false;
                request.Method      = WebRequestMethods.Ftp.MakeDirectory;

                response = request.GetResponse() as FtpWebResponse;
            }

            catch (Exception exception)
            {
                DatabaseAssistant.ReportException(exception);
            }

            finally
            {
                if (request != null)
                {
                    request.Abort();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
        }
Esempio n. 12
0
 public void Abort()
 {
     if (request != null)
     {
         request.Abort();
     }
 }
Esempio n. 13
0
        /// <summary>
        /// 删除FTP服务器文件
        /// </summary>
        /// <param name="remoteFilePath">删除文件的FTP路径和名称(相对FTP根目录)</param>
        /// <param name="ftpServerIP">FTP服务器IP地址</param>
        /// <param name="loginName">FTP 服务器登录名</param>
        /// <param name="loginPassword">FTP 服务器登录密码</param>
        /// <returns>上传是否成功</returns>
        public bool Delete(string remoteFilePath, string ftpServerIP, string loginName, string loginPassword)
        {
            string        uri    = "ftp://" + ftpServerIP + "/" + remoteFilePath;
            FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(uri));

            reqFTP.Credentials = new NetworkCredential(loginName, loginPassword); // ftp用户名和密码
            reqFTP.KeepAlive   = false;                                           // 在一个命令之后被执行 默认为true,连接不会被关闭
            reqFTP.Method      = WebRequestMethods.Ftp.DeleteFile;                // 指定执行什么命令
            FtpWebResponse response = null;

            try
            {
                response = (FtpWebResponse)reqFTP.GetResponse();
            }
            catch (Exception ex)
            {
                reqFTP.Abort();
                LogHelper.Error(typeof(FTPHelper), "FilePath:" + remoteFilePath, ex);
                return(false);
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
            return(true);
        }
Esempio n. 14
0
        public bool subirArchivo(string rutaDestino, string rutaOriginal)
        {
            try
            {
                string RutaCompleta = this.servidor + this.rutaBaseApp + rutaDestino;
                this.ftp        = (FtpWebRequest)FtpWebRequest.Create(RutaCompleta);
                ftp.Credentials = new NetworkCredential(this.usuario, this.password);

                ftp.KeepAlive = true;
                ftp.UseBinary = true;
                ftp.Method    = WebRequestMethods.Ftp.UploadFile;
                FileStream fs = System.IO.File.OpenRead(rutaOriginal);

                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();

                Stream ftpstream = ftp.GetRequestStream();

                ftpstream.Write(buffer, 0, buffer.Length);
                ftpstream.Close();
                ftp.Abort();
                return(true);
            }
            catch (Exception ex)
            {
                this.mensajeError = ex.Message;
                this.ftp.Abort();
                return(false);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// 获取文件大小
        /// </summary>
        /// <param name="file">ip服务器下的相对路径</param>
        /// <returns>文件大小</returns>
        public long GetFileSize(string file)
        {
            StringBuilder result = new StringBuilder();

            //FtpWebRequest request;
            try
            {
                string        uri     = "ftp://" + this.ftpServerName + file;
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);

                //request = (FtpWebRequest)FtpWebRequest.Create(new Uri(path + file));
                request.UseBinary   = true;
                request.Credentials = new NetworkCredential(this.loginName, this.password);//设置用户名和密码
                request.Method      = WebRequestMethods.Ftp.GetFileSize;

                long dataLength = request.GetResponse().ContentLength;//(单位:字节)
                request.GetResponse().Close();
                request.Abort();
                Console.Out.WriteLine(file + ":" + dataLength + "字节");

                return(dataLength);
            }
            catch (Exception ex)
            {
                Console.WriteLine("获取文件大小出错:" + ex.Message);
                return(-1);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// This function determines if an FTP connection is available at the specified host.
        /// Note: It doesn't download any files but just checks if the FTP connection
        /// is available by determining if a directory listing is available.
        /// NOTE: The directory listing is not used for anything except a connection check.
        /// </summary>
        /// <param name="ftpHost">The URL of the VCU</param>
        /// <returns>true if the FTP connection is available; false otherwise</returns>
        private Boolean TestFTPConnection(string ftpHost)
        {
            Boolean       ftpConnectionState;
            FtpWebRequest requestDir = (FtpWebRequest)FtpWebRequest.Create(ftpHost);

            try
            {
                requestDir.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                // Allow 5000 msecs for an FTP response. This timeout is valid when a connection
                // suddenly goes down. Typically, if the connection never existed, the code immediately
                // falls thru to catch()
                requestDir.Timeout = 5000;
                requestDir.GetResponse();
                ftpConnectionState = true;
            }
            catch
            {
                ftpConnectionState = false;
            }
            finally
            {
                requestDir.Abort();
            }
            return(ftpConnectionState);
        }
Esempio n. 17
0
            internal static string[] TreeDir(string Path)
            {
                FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(Server + Path.Replace("\\", "/"));

                ftpRequest.Credentials = ServerAcess;
                ftpRequest.KeepAlive   = false;
                ftpRequest.Method      = WebRequestMethods.Ftp.ListDirectory;
                FtpWebResponse response     = (FtpWebResponse)ftpRequest.GetResponse();
                StreamReader   streamReader = new StreamReader(response.GetResponseStream());

                string[] files = new string[0];

                string line = streamReader.ReadLine();

                while (!string.IsNullOrEmpty(line))
                {
                    if (line == "." || line == "..")
                    {
                        line = streamReader.ReadLine();
                    }
                    else
                    {
                        string[] temp = new string[files.Length + 1];
                        files.CopyTo(temp, 0);
                        temp[files.Length] = line;
                        files = temp;
                        line  = streamReader.ReadLine();
                    }
                }
                streamReader.Close();
                ftpRequest.Abort();
                return(files);
            }
Esempio n. 18
0
        public EntryInfoBase[] ListRepositories(string path)
        {
            List <EntryInfoBase> entries = new List <EntryInfoBase>();

            //create ftp web request
            FtpWebRequest request = this.CreateWebRequest(WebRequestMethods.Ftp.ListDirectoryDetails, this.GetValidPath(this._host, path));

            //get ftp response
            FtpWebResponse response = this.GetResponse(request);

            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                //add all file path
                while (!reader.EndOfStream)
                {
                    EntryInfoBase entry = EntryInfoBase.Parse(reader.ReadLine(), path);
                    entries.Add(entry);
                }
            }

            //Close connection
            response.Close();
            request.Abort();

            return(entries.ToArray());
        }
Esempio n. 19
0
 public void Dispose()
 {
     if (reqFTP != null)
     {
         reqFTP.Abort();
     }
 }
Esempio n. 20
0
 void DeleteFtpFile(string xFile)
 {
     if (!string.IsNullOrEmpty(xFile))
     {
         FileInfo x = new FileInfo(xFile);
         xFile = x.Name;
         string        ftpUrl        = System.Configuration.ConfigurationManager.AppSettings["ftpUrl"].ToString();
         FtpWebRequest deleteRequest = (FtpWebRequest)WebRequest.Create(ftpUrl + xFile);
         deleteRequest.Method = WebRequestMethods.Ftp.DeleteFile;
         string userId = System.Configuration.ConfigurationManager.AppSettings["ftpUser"].ToString();
         string passwd = System.Configuration.ConfigurationManager.AppSettings["ftpAccess"].ToString();
         deleteRequest.Credentials = new NetworkCredential(userId, passwd);
         deleteRequest.KeepAlive   = true;
         if (FilesInDirectory(xFile))
         {
             try
             {
                 FtpWebResponse response = (FtpWebResponse)deleteRequest.GetResponse();
                 string         msg      = response.ExitMessage + "\n";
                 msg += response.BannerMessage + "\n";
                 msg += response.StatusCode + "\n";
                 msg += response.StatusDescription;
                 if (response.StatusDescription.Contains("DELE"))
                 {
                     ListFilesInDirectory();
                 }
                 response.Close();
                 deleteRequest.Abort();
             }
             catch (WebException e)
             {
             }
         }
     }
 }
Esempio n. 21
0
        public void Upload(Stream stream, string remoteFile)
        {
            FtpWebRequest request = this.CreateWebRequest(WebRequestMethods.Ftp.UploadFile, this.GetValidFile(this._host, remoteFile));

            //get ftp response
            FtpWebResponse response = this.GetResponse(request);

            if (stream.CanSeek)
            {
                request.ContentLength = stream.Length;
            }

            //Upload data
            using (Stream remoteStream = request.GetRequestStream())
            {
                //Copy stream to remtoe stream
                this.Copy(stream, remoteStream);

                //Close stream
                remoteStream.Close();
            }

            //Close connection
            response.Close();
            request.Abort();
        }
Esempio n. 22
0
        /// <summary>
        /// Get the list of entries in current Directory
        /// </summary>
        public List <Item> ListDirectoryExtended()
        {
            string s;

            FtpWebRequest ftp = GetRequest(WebRequestMethods.Ftp.ListDirectoryDetails);

            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                {
                    s = sr.ReadToEnd();
                    sr.Close();
                    response.Close();
                }

            ftp.Abort();

            List <Item> files = new List <Item>();

            foreach (string fl in s.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                Item it = new Item(fl);
                if (it.Style == Item.ListStyle.Unknown)
                {
                    continue;
                }
                if (it.IsDirectory && (it.Name == "." || it.Name == ".."))
                {
                    continue;
                }

                files.Add(it);
            }

            return(files);
        }
Esempio n. 23
0
        public static int UploadFtp(string filePath, string ftpServerIP, string ftpUserID, string ftpPassword)
        {
            FileInfo      info    = new FileInfo(filePath);
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + info.Name));

            try
            {
                request.Credentials   = new NetworkCredential(ftpUserID, ftpPassword);
                request.KeepAlive     = false;
                request.Method        = "STOR";
                request.UseBinary     = true;
                request.ContentLength = info.Length;
                int        count         = 0x800;
                byte[]     buffer        = new byte[count];
                FileStream stream        = info.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                Stream     requestStream = request.GetRequestStream();
                for (int i = stream.Read(buffer, 0, count); i != 0; i = stream.Read(buffer, 0, count))
                {
                    requestStream.Write(buffer, 0, i);
                }
                requestStream.Close();
                stream.Close();
                return(0);
            }
            catch (Exception exception)
            {
                request.Abort();
                LogHelper.LogError(exception);
                return(-2);
            }
        }
Esempio n. 24
0
        public void UploadFile2FTP(string fileName, string content)
        {
            //string message = "Upload Processing Completed";

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(gUIPreferSetup.Current.Url + fileName));

            request.Credentials = new NetworkCredential(gUIPreferSetup.Current.UserName, gUIPreferSetup.Current.Password);
            request.Method      = WebRequestMethods.Ftp.UploadFile;

            byte[] data = System.Text.Encoding.UTF8.GetBytes(content);

            request.ContentLength = data.Length;

            Stream requestStream = request.GetRequestStream();

            requestStream.Write(data, 0, data.Length);
            requestStream.Close();
            requestStream.Dispose();

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                response.Close();
                /// Close FTP
                request.Abort();

                //throw new PXOperationCompletedException(message);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Get the list of entries in current Directory
        /// </summary>
        public List <string> ListDirectory()
        {
            string s;

            FtpWebRequest ftp = GetRequest(WebRequestMethods.Ftp.ListDirectory);

            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
                using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                {
                    s = sr.ReadToEnd();
                    sr.Close();
                    response.Close();
                }

            ftp.Abort();

            List <string> files = new List <string>();

            foreach (string fl in s.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (fl == "." || fl == "..")
                {
                    continue;
                }

                files.Add(Path.GetFileName(fl));
            }

            return(files);
        }
Esempio n. 26
0
        private byte[] GetFileSegmentFromFtp(FtpParameters ftpParameters, string ftpFilename, long offset, bool eof, int segmentSize)
        {
            FtpWebRequest ftpWebRequest = GetFtpRequest(ftpParameters, ftpFilename);

            ftpWebRequest.ContentOffset = offset;
            ftpWebRequest.Method        = WebRequestMethods.Ftp.DownloadFile;
            FtpWebResponse response = GetFtpResponse(ftpWebRequest);

            Stream responseStream = response.GetResponseStream();

            if (responseStream == null)
            {
                throw new ApplicationException("response.GetResponseStream() returned no stream");
            }

            BinaryReader reader = new BinaryReader(responseStream);

            byte[] returnValue = reader.ReadBytes(segmentSize);

            if (!eof)
            {
                ftpWebRequest.Abort();
            }

            reader.Close();
            return(returnValue);
        }
Esempio n. 27
0
        public void CommitUploadStream(params object[] arg)
        {
            // convert the args
            // FtpService svc = arg[0] as FtpService;
            FtpWebRequest uploadRequest   = arg[1] as FtpWebRequest;
            BaseFileEntry fileSystemEntry = arg[2] as BaseFileEntry;

#if !WINDOWS_PHONE && !ANDROID
            WebRequestStream requestStream = arg[3] as WebRequestStream;

            // close the stream
            requestStream.Close();

            // close conncetion
            uploadRequest.Abort();

            // check if all data was written into stream
            if (requestStream.WrittenBytes != uploadRequest.ContentLength)
            {
                // nothing todo request was aborted
                return;
            }
#endif
            // adjust the lengt
#if !WINDOWS_PHONE && !ANDROID
            fileSystemEntry.Length = uploadRequest.ContentLength;
#endif
        }
Esempio n. 28
0
        //创建目录
        public Boolean FtpMakeDir(string localFile)
        {
            FtpWebRequest req = CreateFtpWebRequest(ftpUristring + localFile, WebRequestMethods.Ftp.MakeDirectory);

            try
            {
                FtpWebResponse response = (FtpWebResponse)req.GetResponse();
                response.Close();
            }
            catch (Exception)
            {
                req.Abort();
                return(false);
            }
            req.Abort();
            return(true);
        }
Esempio n. 29
0
 public void Close()
 {
     if (null != this.reqFTP)
     {
         reqFTP.Abort();
         reqFTP = null;
     }
 }
        public void DeleteFtpFiles(string ftpAddress)
        {
            try
            {
                _ftpRequest             = (FtpWebRequest)WebRequest.Create(ftpAddress);
                _ftpRequest.Credentials = new NetworkCredential(_username, _password);
                _ftpRequest.UsePassive  = true;
                _ftpRequest.UseBinary   = true;
                _ftpRequest.KeepAlive   = false;
                _ftpRequest.Method      = WebRequestMethods.Ftp.ListDirectory;
                var response = (FtpWebResponse)_ftpRequest.GetResponse();

                var responseStream = response.GetResponseStream();
                var files          = new List <string>();
                var reader         = new StreamReader(responseStream);
                while (!reader.EndOfStream)
                {
                    files.Add(reader.ReadLine());
                }
                reader.Close();
                responseStream.Dispose();

                foreach (var fileName in files)
                {
                    var parentDirectory = "";
                    if (fileName.Contains(".pdf"))
                    {
                        var ftpPath = ftpAddress + fileName;
                        var request = (FtpWebRequest)WebRequest.Create(ftpPath);
                        request.UsePassive  = true;
                        request.UseBinary   = true;
                        request.KeepAlive   = false;
                        request.Credentials = new NetworkCredential(_username, _password);
                        request.Method      = WebRequestMethods.Ftp.DeleteFile;
                        var ftpWebResponse = (FtpWebResponse)request.GetResponse();
                        ftpWebResponse.Close();
                    }
                    else
                    {
                        parentDirectory += $"{fileName}/";
                        try
                        {
                            DeleteFtpFiles($"{ftpAddress}/{parentDirectory}");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _ftpRequest.Abort();
                Console.WriteLine(e);
            }
        }