예제 #1
0
        public void ftpFileDownloadProcess(String[,] _downloadFiles)
        {
            for (int fileCnt = 0; fileCnt < _downloadFiles.GetLength(0); fileCnt++)
            {
                long fws = 0;
                // 파일을 다운로드한다.

                var            res  = _cu.Connect(_downloadFiles[fileCnt, 1], WebRequestMethods.Ftp.DownloadFile, ref fws, cf.FtpPath, cf.FtpUser, cf.FtpPass);
                FtpWebResponse resp = res.GetResponse() as FtpWebResponse;

                using (var stream = resp.GetResponseStream())
                {
                    // stream을 통해 파일을 작성한다.
                    using (var fs = System.IO.File.Create(cf.LocalDownloadPath + "\\" + _downloadFiles[fileCnt, 0]))
                    {
                        try
                        {
                            if (this.InvokeRequired)
                            {
                                this.Invoke(new MethodInvoker(delegate()
                                {
                                    label4.Text = "다운로드파일 : " + _downloadFiles[fileCnt, 0];
                                }));
                            }

                            byte[] buffer = new byte[10 * 1024 * 1024];
                            int    read;
                            long   total = 0;
                            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                fs.Write(buffer, 0, read);
                                total += read;

                                int percents = (int)(total * 100 / fws);

                                strSpeed = "다운로드 진행률 : " + string.Format("{0:#,##0}kb", total) + " / " + string.Format("{0:#,##0}kb", fws) + "(" + percents + "%)";

                                backgroundWorker1.ReportProgress(percents);
                            }

                            res = null;
                            resp.Dispose();
                            stream.Flush();
                            stream.Close();
                            stream.Dispose();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                            res = null;
                            resp.Dispose();
                            throw ex;
                        }
                    }
                }
            }
        }
예제 #2
0
 /// <summary>
 /// Sube la imagen al servidor ftp.
 /// </summary>
 /// <param name="imgNombre">Nombre de la imagen.</param>
 /// <param name="image">Bytes de la imagen</param>
 public bool UploadBitmapAsync(string imgNombre, byte[] image, string path)
 {
     try
     {
         FtpWebRequest client = (FtpWebRequest)WebRequest.Create("ftp://cloud.worklabs.mx/" + path + imgNombre);
         client.Method      = WebRequestMethods.Ftp.UploadFile;
         client.UsePassive  = true;
         client.Credentials = new NetworkCredential(@"worklabscloud", @"Worklabscloud!");
         Stream requestStream = client.GetRequestStream();
         requestStream.Write(image, 0, image.Length);
         requestStream.Close();
         FtpWebResponse response = (FtpWebResponse)client.GetResponse();
         response.Close();
         response.Dispose();
         client = null;
         GC.Collect();
         //client.Abort();
         return(true);
     }
     catch (Exception e)
     {
         SlackLogs.SendMessage(e.Message, GetType().Name, "UploadBitmapAsync");
         return(false);
     }
 }
예제 #3
0
            public static List <string> getFTPDirectoryDetails(string FTPAddress, string FTPUser, string FTPPass)
            {
                //check directory contents
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPAddress);

                request.KeepAlive   = true;
                request.Method      = WebRequestMethods.Ftp.ListDirectoryDetails;
                request.Credentials = new NetworkCredential(FTPUser, FTPPass);
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                //get list of csvs
                Stream        responseStream = response.GetResponseStream();
                StreamReader  reader         = new StreamReader(responseStream);
                List <string> directories    = new List <string>();

                //create the output
                string line = reader.ReadLine();

                while (!string.IsNullOrEmpty(line))
                {
                    directories.Add(line);
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Dispose();
                return(directories);
            }
예제 #4
0
    public void FileAddWrite(string text, string url, TaskEvent finished = null, ErrorEvent error = null)
    {
        try
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(accessUrlBase + url));
            request.Method = WebRequestMethods.Ftp.AppendFile;

            byte[] fileContents = Encoding.UTF8.GetBytes(text);

            request.ContentLength = fileContents.Length;
            request.Credentials   = icr;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            response.Close();
            requestStream.Dispose();
            response.Dispose();
            finished?.Invoke();
        }
        catch (WebException e)
        {
            error?.Invoke(((FtpWebResponse)e.Response).StatusDescription);
        }
    }
예제 #5
0
 public static bool SendFilesByFTP(string password, string userName, string url, string destinationFtp)
 {
     try
     {
         System.Uri    serverUri = new System.Uri(destinationFtp);
         FtpWebRequest request   = (FtpWebRequest)WebRequest.Create(serverUri);
         request.Method              = WebRequestMethods.Ftp.UploadFile;
         request.UseBinary           = true;
         request.UsePassive          = true;
         request.KeepAlive           = false;
         request.Timeout             = System.Threading.Timeout.Infinite;
         request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
         request.Credentials         = new NetworkCredential(userName, password);
         using (StreamReader sourceStream = new StreamReader(url))
         {
             MemoryStream memstream = new MemoryStream();
             sourceStream.BaseStream.CopyTo(memstream);
             byte[] fileContents = memstream.ToArray();
             sourceStream.Close();
             request.ContentLength = fileContents.Length;
             Stream requestStream = request.GetRequestStream();
             requestStream.Write(fileContents, 0, fileContents.Length);
             requestStream.Close();
             FtpWebResponse response = (FtpWebResponse)request.GetResponse();
             response.Close();
             response.Dispose();
             return(true);
         }
     }
     catch (Exception e)
     {
         return(ToBoolean(e.Message, "", ""));
     }
 }
예제 #6
0
        public void deleteFile(String realPath, bool USESSL)
        {
            FtpWebResponse f = get_reader(realPath, USESSL, WebRequestMethods.Ftp.DeleteFile);

            f.Close();
            f.Dispose();
        }
예제 #7
0
        public static void UploadFile(string ftpserver, string user, string password, string relPath, byte[] data)
        {
            var request = GetRequest(ftpserver + "/" + relPath);

            request.Method      = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(user, password);
            request.UseBinary   = true;

            request.ContentLength = data.Length;
            Stream requestStream = request.GetRequestStream();

            requestStream.Write(data, 0, data.Length);
            requestStream.Close();
            requestStream.Flush();
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            if (response.StatusCode != FtpStatusCode.ClosingData)
            {
                throw new Exception("");
            }

            requestStream.Dispose();
            response.Close();
            response.Dispose();
        }
예제 #8
0
        /// <summary>
        /// Checks if a given file exists on the remote FTP server.
        /// </summary>
        /// <returns><c>true</c>, if the file exists, <c>false</c> otherwise.</returns>
        /// <param name="remotePath">Remote path.</param>
        public bool DoesRemoteFileExist(string remotePath)
        {
            FtpWebRequest request = CreateFtpWebRequest(remotePath,
                                                        Config.GetRemoteUsername(),
                                                        Config.GetRemotePassword());
            FtpWebResponse response = null;

            try
            {
                response = (FtpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (FtpWebResponse)ex.Response;
                if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    return(false);
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Dispose();
                }
            }

            return(true);
        }
예제 #9
0
        /// <summary>
        /// 列出指定资源定位符的目录详细列表
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public string[] DirectoryListDetail(Uri uri)
        {
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri);

            ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
            //ftpRequest.Credentials = new NetworkCredential("ftp01", "yzgjtsjt_881202");
            ftpRequest.Credentials        = new NetworkCredential(this.username, this.password);
            ftpRequest.ImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Anonymous;
            ftpRequest.KeepAlive          = true;
            ftpRequest.UseBinary          = true;
            ftpRequest.Timeout            = 10000;

            ftpRespose = (FtpWebResponse)ftpRequest.GetResponse();
            Stream responseStream = ftpRespose.GetResponseStream();

            StreamReader streamReader = new StreamReader(responseStream, Encoding.Default);

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

            while (streamReader.Peek() != -1)
            {
                directoryList.Add(streamReader.ReadLine());
            }
            ftpRespose.Close();
            ftpRespose.Dispose();
            return(directoryList.ToArray());
        }
예제 #10
0
        private void _downloadFromFtp(string path, string username, string password, Stream copyHere, string method)
        {
            var request = (FtpWebRequest)WebRequest.Create(path);

            request.Credentials = new NetworkCredential(username, password);
            request.EnableSsl   = false;
            request.Method      = method;
            FtpWebResponse response = null;

            while (true)
            {
                try
                {
                    response = (FtpWebResponse)request.GetResponse();
                    response.GetResponseStream().CopyTo(copyHere);
                    return;
                }
                catch (Exception exp)
                {
                    logger.Log("Произошла ошибка в процессе запроса к FTP").Wait();
                    logger.Log(exp.Message).Wait();
                    logger.Log("Жду одну секунду").Wait();
                    Thread.Sleep(1000);
                    logger.Log("Повторяю запрос").Wait();
                }
                finally
                {
                    if (response != null)
                    {
                        response.Dispose();
                    }
                }
            }
        }
 private void Download_Ftp_File(string p, string Source_Path)
 {
     try
     {
         FtpWebRequest reqFTP;
         string        Folder_Path = "C:\\OMS\\Temp";
         if (!Directory.Exists(Folder_Path))
         {
             Directory.CreateDirectory(Folder_Path);
         }
         string     localPath    = Folder_Path + "\\" + p;
         FileStream outputStream = new FileStream(localPath, FileMode.Create);
         reqFTP             = (FtpWebRequest)WebRequest.Create(new Uri(Source_Path));
         reqFTP.Method      = WebRequestMethods.Ftp.DownloadFile;
         reqFTP.UseBinary   = true;
         reqFTP.Credentials = new NetworkCredential(Ftp_User_Name, Ftp_Password);
         FtpWebResponse response  = (FtpWebResponse)reqFTP.GetResponse();
         Stream         ftpStream = response.GetResponseStream();
         ftpStream.CopyTo(outputStream);
         ftpStream.Dispose();
         outputStream.Dispose();
         response.Dispose();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.ToString() + "Problem in Downloading Files please Check with Administrator");
     }
 }
예제 #12
0
        private void Dispose(bool disposing)
        {
            if (_isDisposed)
            {
                return;
            }

            if (disposing)
            {
                if (_streamReader != null)
                {
                    _streamReader.Close();

                    _streamReader.Dispose();
                }

                if (_ftpWebResponse != null)
                {
                    _ftpWebResponse.Close();

                    _ftpWebResponse.Dispose();
                }
            }

            _isDisposed = true;
        }
예제 #13
0
파일: ftp.cs 프로젝트: tofilagman/z.Web
        public void Dispose()
        {
            ftpRequest = null;
            ftpResponse?.Dispose();
            ftpStream?.Dispose();

            GC.Collect();
            GC.SuppressFinalize(this);
        }
예제 #14
0
        public async Task RemoveDirectoryAsync(string remotePath)
        {
            FtpWebRequest request = CreateRequest(remotePath);

            request.Method = WebRequestMethods.Ftp.RemoveDirectory;
            FtpWebResponse response = await GetResponseAsync(request);

            response?.Dispose();
        }
예제 #15
0
        public async Task DeleteFileAsync(string remotePath)
        {
            FtpWebRequest request = CreateRequest(remotePath);

            request.Method = WebRequestMethods.Ftp.DeleteFile;
            FtpWebResponse response = await GetResponseAsync(request);

            response?.Dispose();
        }
예제 #16
0
        private void button_sendData_Click(object sender, EventArgs e)
        {
            this.label_resultmsg.Text      = "";
            this.label_resultmsg.ForeColor = Color.Green;
            try
            {
                if (checkBox_TempDev.Checked == true)
                {
                    var           fileName = int.Parse(GetLastFTPName()) + 1;
                    var           ftpUrl   = ConfigurationManager.AppSettings["ftpUrl"];
                    FtpWebRequest request  = (FtpWebRequest)WebRequest.Create(ftpUrl + "/" + fileName.ToString("00000") + ".xml");

                    request.Method      = WebRequestMethods.Ftp.UploadFile;
                    request.Credentials = new NetworkCredential("*****@*****.**", "Qwerty1");

                    var doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement("data"));

                    Random rnd = new Random();
                    doc.Root.Add(new XElement("date", DateTime.Now.ToString()));
                    doc.Root.Add(new XElement("value", rnd.Next(0, 50).ToString()));

                    Stream requestStream = request.GetRequestStream();
                    doc.Save(requestStream);
                    requestStream.Close();

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

                    response.Close();
                    response.Dispose();
                    this.label_resultmsg.Text = "Data is added ";
                }

                if (checkBox_PresDev.Checked == true)
                {
                    var WebSeviceUrl = ConfigurationManager.AppSettings["webServiceUrl"];
                    using (var client = new HttpClient())
                    {
                        Random     rnd = new Random();
                        DeviceData p   = new DeviceData {
                            Date = DateTime.Now, Value = rnd.Next(600, 900)
                        };
                        client.BaseAddress = new Uri(WebSeviceUrl);
                        var respons = client.PostAsJsonAsync("api/DeviceValue/AddData", p).Result;
                        if (respons.StatusCode == HttpStatusCode.OK)
                        {
                            this.label_resultmsg.Text = "Data is added ";
                        }
                    }
                }
                ;
            }
            catch (Exception ex)
            {
                this.label_resultmsg.ForeColor = Color.Red;
                this.label_resultmsg.Text     += $"There were errors";
            }
        }
예제 #17
0
        /// <summary>
        /// 获取文件大小
        /// </summary>
        /// <param name="str">文件路径</param>
        /// <returns></returns>
        public double GetFileSize(String str, bool USESSL)
        {
            FtpWebResponse res    = get_reader(str, USESSL, WebRequestMethods.Ftp.GetFileSize);
            double         length = res.ContentLength;

            res.Close();
            res.Dispose();
            return(length);
        }
예제 #18
0
파일: FTP.cs 프로젝트: OSM-Made/Orbis-Suite
        public List <FtpFileInfo> GetDir(string Dir)
        {
            try
            {
                string        Directory = Dir;
                FtpWebRequest ftp       = (FtpWebRequest)FtpWebRequest.Create($"ftp://{ Target.Info.IPAddr }:6904/{Directory}");

                ftp.Credentials = new NetworkCredential("anonymous", "anonymous");

                ftp.UseBinary  = true;
                ftp.UsePassive = true;
                ftp.KeepAlive  = false;

                ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

                FtpWebResponse ftpResponse = (FtpWebResponse)ftp.GetResponse();

                Stream ftpStream = ftpResponse.GetResponseStream();

                StreamReader ftpReader = new StreamReader(ftpStream);

                string RawData = ftpReader.ReadToEnd();

                ftpReader.Dispose();
                ftpStream.Dispose();
                ftpResponse.Dispose();
                ftp = null;

                string[]           RawArray = RawData.Split("\n".ToCharArray());
                List <FtpFileInfo> List     = new List <FtpFileInfo>();

                foreach (string Member in RawArray)
                {
                    Match  match    = FtpListDirectoryDetailsRegex.Match(Member);
                    string FileName = match.Groups["fileName"].Value;

                    if (Member.Length == 0 || (FileName.StartsWith(".") && FileName.Length == 2))
                    {
                        continue;
                    }

                    List.Add(new FtpFileInfo(
                                 Member.StartsWith("d"),
                                 match.Groups["month"].Value + match.Groups["day"].Value + match.Groups["yearTime"].Value,
                                 match.Groups["fileName"].Value.Replace("\r", "")
                                 ));
                }

                return(List);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            return(new List <FtpFileInfo>());
        }
예제 #19
0
        public async Task RenameAsync(string remotePath, string renameTo)
        {
            FtpWebRequest request = CreateRequest(remotePath);

            request.Method   = WebRequestMethods.Ftp.Rename;
            request.RenameTo = renameTo;
            FtpWebResponse response = await GetResponseAsync(request);

            response?.Dispose();
        }
 /// <summary>
 /// Возвращает флаг указывающий - существует ли заданная папка на сервере
 /// </summary>
 /// <param name="username"></param>
 /// <param name="Pass"></param>
 /// <param name="Urlpath"></param>
 /// <param name="FilelocalPath"></param>
 /// <returns></returns>
 internal static bool IsFolderCreated(string username, string Pass, string Urlpath, string textfile = "/|_CURRENT_")
 {
     try
     {
         FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(Urlpath + textfile);
         ftp.Credentials = new NetworkCredential(username, Pass);
         ftp.Method      = WebRequestMethods.Ftp.MakeDirectory;
         FtpWebResponse resp = (FtpWebResponse)ftp.GetResponse();
         resp.Dispose();
         return(true);
     }
     catch (Exception) { return(false); }
 }
 /// <summary>
 /// Создает папку на сервере через FTP.
 /// </summary>
 /// <param name="URLpath"></param>
 /// <param name="Pass"></param>
 /// <param name="username"></param>
 /// <param name="folder_order">Название папки должно соответствовать номеру договора</param>
 internal static void FolderCreate(string URLpath, string Pass, string username, string folder_order)
 {
     try
     {
         string        fullPath = URLpath + "/" + folder_order;
         FtpWebRequest zapros   = (FtpWebRequest)WebRequest.Create(fullPath);
         zapros.Credentials = new NetworkCredential(username, Pass);
         zapros.Method      = WebRequestMethods.Ftp.MakeDirectory;
         FtpWebResponse resp = (FtpWebResponse)zapros.GetResponse();
         resp.Dispose();
     }
     catch (Exception ex)
     {
         BOX.ShowError(ex.Message, ex.Source);
     }
 }
예제 #22
0
        /// <summary>
        /// Close, dispose and nullify _stream and _response
        /// </summary>
        private void CloseConnection()
        {
            // Clean up response if exists
            if (_response != null)
            {
                _response.Dispose();
                _response = null;
            }

            // Clean up stream if exists
            if (_stream != null)
            {
                _stream.Dispose();
                _stream = null;
            }
        }
예제 #23
0
        static void ExecuteRequest(FtpWebRequest request)
        {
            FtpWebResponse response = null;

            try
            {
                response = (FtpWebResponse)request.GetResponse();
            }
            finally
            {
                if (response != null)
                {
                    response.Dispose();
                }
            }
        }
예제 #24
0
        private CResultAErreurType <CFichierLocalTemporaire> GetFileFromFtp(CActionCopierLocalDansGed.CParametresCopierLocalDansGed parametre)
        {
            CResultAErreurType <CFichierLocalTemporaire> result = new CResultAErreurType <CFichierLocalTemporaire>();
            string strExt    = "dat";
            int    nPosPoint = parametre.NomFichierLocal.LastIndexOf(".");

            if (nPosPoint >= 0)
            {
                strExt = parametre.NomFichierLocal.Substring(nPosPoint + 1);
            }
            CFichierLocalTemporaire fichierTemporaireFromFTP = new CFichierLocalTemporaire(strExt);

            fichierTemporaireFromFTP.CreateNewFichier();

            using (FileStream streamDest = new FileStream(
                       fichierTemporaireFromFTP.NomFichier,
                       FileMode.CreateNew,
                       FileAccess.Write))
            {
                try
                {
                    FtpWebRequest req = (FtpWebRequest)WebRequest.Create(parametre.NomFichierLocal);
                    req.Method      = WebRequestMethods.Ftp.DownloadFile;
                    req.Credentials = new NetworkCredential(parametre.User, parametre.Password);

                    FtpWebResponse response   = (FtpWebResponse)req.GetResponse();
                    Stream         respStream = response.GetResponseStream();
                    byte[]         buffer     = new byte[256];
                    int            nNbLus     = 0;
                    while ((nNbLus = respStream.Read(buffer, 0, 256)) != 0)
                    {
                        streamDest.Write(buffer, 0, nNbLus);
                    }
                    respStream.Close();
                    respStream.Dispose();
                    response.Close();
                    response.Dispose();
                    result.DataType = fichierTemporaireFromFTP;
                }
                catch (Exception e)
                {
                    result.EmpileErreur(new CErreurException(e));
                }
                streamDest.Close();
            }
            return(result);
        }
예제 #25
0
        public async Task UploadFileAsync(string remotePath, string localPath)
        {
            FtpWebRequest request = CreateRequest(remotePath);

            request.Method = WebRequestMethods.Ftp.UploadFile;

            using (Stream ftpStream = request.GetRequestStream()) {
                Debug.Assert(ftpStream != null, nameof(ftpStream) + " != null");
                using (FileStream localStream = File.Open(localPath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                    // ReSharper disable once PossibleNullReferenceException
                    await localStream.CopyToAsync(ftpStream, 2048);
                }
            }

            FtpWebResponse response = await GetResponseAsync(request);

            response?.Dispose();
        }
예제 #26
0
 private bool Exists(string path, FTPResourceType type)
 {
     try
     {
         string        ftpPath = string.Format("{0}{1}{2}", this.FTPRequest.Server, this.FTPRequest.BasePath, path);
         FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpPath);
         request.Method      = type == FTPResourceType.Directory ? WebRequestMethods.Ftp.ListDirectoryDetails : WebRequestMethods.Ftp.GetFileSize;
         request.Credentials = new NetworkCredential(this.FTPRequest.UserName, this.FTPRequest.Pwd);
         FtpWebResponse response = (FtpWebResponse)request.GetResponse();
         response.Close();
         response.Dispose();
     }
     catch (WebException ex)
     {
         return(false);
     }
     return(true);
 }
예제 #27
0
        public void FtpDownload(string urlFileName, string ftpUserID, string ftpPassword, string localfilePath, string localfileName)
        {
            FtpWebRequest reqFTP;

            try
            {
                //string fileName = Path.GetFileName(urlFileName);
                //string filePath,
                FileStream outputStream = new FileStream(Path.Combine(localfilePath, localfileName), FileMode.Create);
                reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri(urlFileName));
                reqFTP.Method      = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary   = true;
                reqFTP.UsePassive  = false;
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                FtpWebResponse response  = (FtpWebResponse)reqFTP.GetResponse();
                Stream         ftpStream = response.GetResponseStream();

                long   cl         = response.ContentLength;
                int    bufferSize = 2048;
                int    readCount;
                byte[] buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }

                ftpStream.Close();
                ftpStream.Dispose();
                outputStream.Close();
                outputStream.Dispose();
                response.Close();
                response.Dispose();
                // return buf;
            }
            catch (Exception ex)
            {
                m_loginfo.Error("Error:FtpDownload");
                m_loginfo.Error(ex);
            }
        }
예제 #28
0
        public async Task DeleteFile(string fileName)
        {
            FileInfo fileInfo = new FileInfo(fileName);
            var      url      = _ftpUrl + fileInfo.Name;
            var      ftp      = GetRequest(url);

            ftp.Method = WebRequestMethods.Ftp.DeleteFile;
            string         result         = "";
            FtpWebResponse ftpWebResponse = (FtpWebResponse)(await ftp.GetResponseAsync());
            long           size           = ftpWebResponse.ContentLength;

            using (var stream = ftpWebResponse.GetResponseStream())
                using (var streamReader = new StreamReader(stream))
                {
                    result = await streamReader.ReadToEndAsync();
                }
            ftpWebResponse.Close();
            ftpWebResponse.Dispose();
        }
예제 #29
0
파일: FtpHelper.cs 프로젝트: vist0r/kyubey
        public bool Upload(string localFile, string uri)
        {
            try
            {
                _ftpRequest        = (FtpWebRequest)WebRequest.Create(uri);
                _ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;

                // This example assumes the FTP site uses anonymous logon.
                _ftpRequest.Credentials = new NetworkCredential(_username.Normalize(), _password.Normalize());

                // Copy the contents of the file to the request stream.
                byte[] fileContents;

                fileContents = File.ReadAllBytes(localFile);

                _ftpRequest.UseBinary = true;

                _ftpRequest.ContentLength = fileContents.Length;

                using (Stream requestStream = _ftpRequest.GetRequestStream())
                {
                    requestStream.Write(fileContents, 0, fileContents.Length);
                }

                FtpWebResponse response = (FtpWebResponse)_ftpRequest.GetResponse();


                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"{DateTime.Now} Upload File Succeed:{uri}");
                Console.ResetColor();
                response.Dispose();
                return(true);
            }
            catch (WebException ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"{DateTime.Now} Upload File Failed:{uri}");
                Console.ResetColor();
                return(false);
            }
        }
예제 #30
0
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolDelete_Click(object sender, EventArgs e)
        {
            try
            {
                String fileName = this.Invoke(getName).ToString();
                String type     = this.Invoke(getType).ToString();
                String realPath;
                //路径拼接
                if (currentUrl.ElementAt(currentUrl.Length - 1) == '/')
                {
                    realPath = currentUrl + fileName;
                }
                else
                {
                    realPath = currentUrl + "/" + fileName;
                }

                FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(@realPath);
                //ftpRequest.UseBinary = true;
                ftpRequest.Timeout     = 5000;
                ftpRequest.Credentials = new NetworkCredential(user, pass);
                if (USESSL)
                {
                    ftpRequest.EnableSsl = true;
                    ServicePointManager.ServerCertificateValidationCallback =
                        new RemoteCertificateValidationCallback(ValidateServerCertificate);
                }
                ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
                FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

                //刷新当前文件夹
                enterADirectury(currentUrl);
                ftpResponse.Close();
                ftpResponse.Dispose();
            }
            catch (Exception ex)
            {
                //MessageBox.Show("删除失败!\n\t请检查是否有权限在当前目录下执行删除操作!");
                MessageBox.Show(ex.Message);
            }
        }