Esempio n. 1
0
        //Version taking string/FileInfo
        public bool Download(string sourceFilename, FileInfo targetFI, bool PermitOverwrite)
        {
            //1. check target
            if (targetFI.Exists && !(PermitOverwrite))
            {
                throw (new ApplicationException("Target file already exists"));
            }

            //2. check source
            string target;

            if (sourceFilename.Trim() == "")
            {
                throw (new ApplicationException("File not specified"));
            }
            else if (sourceFilename.Contains("/"))
            {
                //treat as a full path
                target = AdjustDir(sourceFilename);
            }
            else
            {
                //treat as filename only, use current directory
                target = CurrentDirectory + sourceFilename;
            }

            string URI = Hostname + target;

            //3. perform copy
            DownloadFTPRequest = GetRequest(URI);

            //Set request to download a file in binary mode
            DownloadFTPRequest.Method    = System.Net.WebRequestMethods.Ftp.DownloadFile;
            DownloadFTPRequest.UseBinary = true;
            TargetFileInfo = targetFI;

            //Give Message of Command
            FtpConnectEventArgs StartMessage = new FtpConnectEventArgs("COMMAND", "Ftp Connect Start", "CONNECT");

            //OnFtpConnected(this, StartMessage);
            System.Windows.Forms.Application.DoEvents();

            //open request and get response stream
            using (DownloadResponse = (FtpWebResponse)DownloadFTPRequest.GetResponse())
            {
                using (DownloadResponseStream = DownloadResponse.GetResponseStream())
                {
                    //System.Security.AccessControl.FileSecurity fileSecurity = new System.Security.AccessControl.FileSecurity(targetFI.FullName, System.Security.AccessControl.AccessControlSections.All);
                    //targetFI.SetAccessControl(fileSecurity);
                    //loop to read & write to file
                    using (DownloadFileStream = new FileStream(targetFI.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {
                        try
                        {
                            //Give Message of Command
                            FtpConnectEventArgs ConnectMessage = new FtpConnectEventArgs("COMMAND", "Ftp Connected", "CONNECT");
                            //OnFtpConnected(this, ConnectMessage);

                            //Give Message of Command
                            NewMessageEventArgs e = new NewMessageEventArgs("COMMAND", "Download File", "RETR");
                            //OnNewMessageReceived(this, e);
                            byte[] buffer         = new byte[2048];
                            int    read           = 0;
                            Int64  TotalBytesRead = 0;
                            Int64  FileSize       = this.GetFileSize(sourceFilename);
                            DownloadCanceled = false;
                            do
                            {
                                if (DownloadCanceled)
                                {
                                    NewMessageEventArgs CancelMessage = new NewMessageEventArgs("RESPONSE", "Download Canceled.", "CANCEL");

                                    DownloadCanceled = false;
                                    //OnNewMessageReceived(this, CancelMessage);
                                    return(false);
                                }

                                read = DownloadResponseStream.Read(buffer, 0, buffer.Length);
                                DownloadFileStream.Write(buffer, 0, read);
                                TotalBytesRead += read;
                                //Declare Event
                                DownloadProgressChangedArgs DownloadProgress = new DownloadProgressChangedArgs(TotalBytesRead, FileSize);

                                //Progress changed, Raise the event.
                                //OnDownloadProgressChanged(this, DownloadProgress);

                                System.Windows.Forms.Application.DoEvents();
                            } while (!(read == 0));


                            //Get Message and Raise Event
                            NewMessageEventArgs NewMessageArgs = new NewMessageEventArgs("RESPONSE", DownloadResponse.StatusDescription, DownloadResponse.StatusCode.ToString());
                            //OnNewMessageReceived(this, NewMessageArgs);

                            //Declare Event
                            DownloadCompletedArgs Args = new DownloadCompletedArgs("Successful", true);
                            //Raise Event
                            //OnDownloadCompleted(this, Args);

                            DownloadResponseStream.Close();
                            DownloadFileStream.Flush();
                            DownloadFileStream.Close();
                            DownloadFileStream     = null;
                            DownloadResponseStream = null;
                        }
                        catch (Exception ex)
                        {
                            //catch error and delete file only partially downloaded
                            DownloadFileStream.Close();
                            //delete target file as it's incomplete
                            targetFI.Delete();

                            //Decalre Event for Error
                            DownloadCompletedArgs DownloadCompleted = new DownloadCompletedArgs("Error: " + ex.Message, false);
                            //Raise Event
                            //OnDownloadCompleted(this, DownloadCompleted);
                        }
                    }
                    if (DownloadFileStream != null)
                    {
                        DownloadResponseStream.Close();
                    }
                }
                if (DownloadFileStream != null)
                {
                    DownloadResponse.Close();
                }
            }
            return(true);
        }
Esempio n. 2
0
        /// <summary>
        /// Upload a local file to the FTP server
        /// </summary>
        /// <param name="fi">Source file</param>
        /// <param name="targetFilename">Target filename (optional)</param>
        /// <returns></returns>
        public 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)

            //1. check target
            string target;

            if (targetFilename.Trim() == "")
            {
                //Blank target: use source filename & current dir
                target = this.CurrentDirectory + fi.Name;
            }
            else if (targetFilename.Contains("/"))
            {
                //If contains / treat as a full path
                target = AdjustDir(targetFilename);
            }
            else
            {
                //otherwise treat as filename only, use current directory
                target = CurrentDirectory + targetFilename;
            }

            string URI = Hostname + target;

            //perform copy
            UploadFTPRequest = GetRequest(URI);

            //Set request to upload a file in binary
            UploadFTPRequest.Method    = System.Net.WebRequestMethods.Ftp.UploadFile;
            UploadFTPRequest.UseBinary = true;
            //Notify FTP of the expected size
            UploadFTPRequest.ContentLength = fi.Length;
            UploadFileInfo = fi;

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

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

            //open file for reading
            using (UploadFileStream = fi.OpenRead())
            {
                try
                {
                    //open request to send
                    //Give Message of Command
                    FtpConnectEventArgs StartMessage = new FtpConnectEventArgs("COMMAND", "Ftp Connect Start", "CONNECT");
                    //OnFtpConnected(this, StartMessage);
                    System.Windows.Forms.Application.DoEvents();

                    using (UploadStream = UploadFTPRequest.GetRequestStream())
                    {
                        //Give Message of Command
                        FtpConnectEventArgs ConnectMessage = new FtpConnectEventArgs("COMMAND", "Ftp Connected", "CONNECT");
                        //OnFtpConnected(this, ConnectMessage);

                        //Give Message of Command
                        NewMessageEventArgs e = new NewMessageEventArgs("COMMAND", "Upload File", "STOR");
                        //OnNewMessageReceived(this, e);

                        //Get File Size
                        Int64 TotalBytesUploaded = 0;
                        Int64 FileSize           = fi.Length;
                        do
                        {
                            if (UploadCanceled)
                            {
                                NewMessageEventArgs CancelMessage = new NewMessageEventArgs("RESPONSE", "Upload Canceled.", "CANCEL");
                                //OnNewMessageReceived(this, CancelMessage);
                                UploadCanceled = false;
                                return(false);
                            }

                            dataRead = UploadFileStream.Read(content, 0, BufferSize);
                            UploadStream.Write(content, 0, dataRead);
                            TotalBytesUploaded += dataRead;
                            //Declare Event
                            UploadProgressChangedArgs DownloadProgress = new UploadProgressChangedArgs(TotalBytesUploaded, FileSize);

                            //Progress changed, Raise the event.
                            //OnUploadProgressChanged(this, DownloadProgress);

                            System.Windows.Forms.Application.DoEvents();
                        } while (!(dataRead < BufferSize));

                        //Get Message and Raise Event
                        NewMessageEventArgs UPloadResponse = new NewMessageEventArgs("RESPONSE", "File Uploaded!", "STOR");
                        //OnNewMessageReceived(this, UPloadResponse);

                        //Declare Event
                        UploadCompletedArgs Args = new UploadCompletedArgs("Successful", true);
                        //Raise Event
                        //OnUploadCompleted(this, Args);

                        UploadStream.Close();
                    }
                }
                catch (Exception ex)
                {
                    //Declare Event
                    UploadCompletedArgs Args = new UploadCompletedArgs("Error: " + ex.Message, false);
                    //Raise Event
                    OnUploadCompleted(this, Args);
                }
                finally
                {
                    //ensure file closed
                    UploadFileStream.Close();
                }
            }


            UploadFTPRequest = null;
            return(true);
        }