示例#1
0
        private void DeleteDirectory(string path, bool useCommand = true)
        {
            if (useCommand)
            {
                //目前有2种会用到删除文件夹
                // 1.文件上传发现要上传的目录已存在
                // 2.旧的发布版本文件夹
                SshCommand cmd = _sshClient.RunCommand($"set -e;cd ~;\\rm -rf \"{path}\";");
                if (cmd.ExitStatus != 0)
                {
                    this._logger($"Delete directory:{path} fail", LogLevel.Warning);
                }
                return;
            }

            foreach (SftpFile file in _sftpClient.ListDirectory(path))
            {
                if ((file.Name != ".") && (file.Name != ".."))
                {
                    if (file.IsDirectory)
                    {
                        DeleteDirectory(file.FullName);
                    }
                    else
                    {
                        _sftpClient.DeleteFile(file.FullName);
                    }
                }
            }

            _sftpClient.DeleteDirectory(path);
        }
示例#2
0
        protected override async Task <Action <AsyncCodeActivityContext> > ExecuteAsync(AsyncCodeActivityContext context, CancellationToken cancellationToken)
        {
            // Inputs
            var host               = Host.Get(context);
            var port               = Port.Get(context);
            var userName           = UserName.Get(context);
            var password           = Password.Get(context);
            var remoteFileFullPath = RemoteFileFullPath.Get(context);

            ///////////////////////////
            // Add execution logic HERE
            ///////////////////////////
            ///

            using (var sftp = new SftpClient(host, port, userName, password))
            {
                sftp.Connect();
                sftp.DeleteFile(remoteFileFullPath);
                sftp.Disconnect();
            }

            // Outputs
            return((ctx) => {
            });
        }
示例#3
0
        public async Task CopyFile(string fromPath, string toPath)
        {
            if (!_connected)
            {
                throw new InvalidOperationException("SSH not connected");
            }

            if (string.IsNullOrEmpty(fromPath) || string.IsNullOrEmpty(toPath))
            {
                throw new InvalidOperationException("Invalid operation: please provide correct paths");
            }

            if (_sfClient.Exists(toPath))
            {
                ConsoleWriter.Error($"Removing existing docker compose file @ [ {toPath} ]");
                _sfClient.DeleteFile(toPath);
            }

            using (var fileStream = new FileStream(fromPath, FileMode.Open, FileAccess.Read))
            {
                ConsoleWriter.Warning($"Creating new docker compose file @ [ {toPath} ]");

                var _result = _sfClient.BeginUploadFile(fileStream, toPath);
                while (!_result.IsCompleted)
                {
                    await Task.Delay(1000);
                }

                ConsoleWriter.Warning($"Docker compose file created @ [ {toPath} ]");
            }
        }
示例#4
0
        /// <summary>
        /// Elimina un archivo del servidor SFTP.
        /// </summary>
        /// <param name="filePath">Ruta de Archivo/Directorio dentro del servidor.</param>
        /// <returns>Logrado o no logrado.</returns>
        /// <remarks>No validado.</remarks>
        public bool Delete(string filePath)
        {
            bool result = false;

            using (SftpClient client = new SftpClient(Host, User, Pass))
            {
                client.Connect();

                if (client.IsConnected)
                {
                    SftpFile file = client.Get(filePath);
                    if (file.IsDirectory)
                    {
                        client.DeleteDirectory(file.FullName);
                    }
                    else
                    {
                        client.DeleteFile(file.FullName);
                    }
                    result = true;
                    client.Disconnect();
                }
            }

            return(result);
        }
示例#5
0
        public void SftpClient_AwkTableGetRowsCount_RowsCountShouldBe8()
        {
            using (var SftpClient = new SftpClient(_SshCredentials.Host, _SshCredentials.Login, _SshCredentials.Password))
            {
                using (var SshClient = new SshClient(_SshCredentials.Host, _SshCredentials.Login, _SshCredentials.Password))
                {
                    SftpClient.Connect();
                    using (Stream fileStream = File.OpenRead(DataSetsDirectory + "DataTable.txt"))
                    {
                        SftpClient.UploadFile(fileStream, "./DataTable.txt", canOverride: true);
                    }

                    SshClient.Connect();
                    using (var cmd = SshClient.CreateCommand("cat DataTable.txt | awk '/a/{++cnt} END {print \"Count = \", cnt}'"))
                    {
                        cmd.Execute();
                        string cmdOutput = cmd.Result;
                        SftpClient.DeleteFile("./DataTable.txt");
                        SftpClient.Disconnect();
                        SshClient.Disconnect();
                        StringAssert.Equals("Count = 8\n", cmdOutput);
                    }
                }
            }
        }
示例#6
0
        public IEnumerable <string> DownloadFiles(string remoteFiles, string localDirectory, bool deleteRemoteFile = false)
        {
            var downloadedFiles = new List <string>();

            SftpClient ftp = null;

            try
            {
                ftp = new SftpClient(this.host, this.user, this.password);
                if (this.KeepAlive)
                {
                    ftp.KeepAliveInterval = new TimeSpan(0, 0, 30);
                }
                ftp.Connect();
                ftp.ChangeDirectory("\\");

                var directoryName     = Path.GetDirectoryName(remoteFiles);
                var remoteFileInfos   = this.GetDirectoryList(directoryName);
                var remoteFilePattern = Path.GetFileName(remoteFiles);

                foreach (var remoteFileInfo in remoteFileInfos)
                {
                    if (string.IsNullOrEmpty(remoteFilePattern) || FileUtil.MatchesWildcard(remoteFileInfo.Name, remoteFilePattern))
                    {
                        var localFileName = Path.Combine(localDirectory, Path.GetFileName(remoteFileInfo.Name));

                        using (var fileStream = File.OpenWrite(localFileName))
                        {
                            ftp.DownloadFile(remoteFileInfo.FullName, fileStream);
                            fileStream.Close();
                        }

                        downloadedFiles.Add(remoteFileInfo.FullName);

                        if (deleteRemoteFile == true)
                        {
                            ftp.DeleteFile(remoteFileInfo.FullName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                if (ftp != null)
                {
                    if (ftp.IsConnected)
                    {
                        ftp.Disconnect();
                    }

                    ftp.Dispose();
                }
            }

            return(downloadedFiles);
        }
示例#7
0
        public void SftpClient_SedDeleteCommentsAndEmptyLinesInFile_FileShouldNotContainCommentsAndEmptyLines()
        {
            using (var SftpClient = new SftpClient(_SshCredentials.Host, _SshCredentials.Login, _SshCredentials.Password))
            {
                using (var SshClient = new SshClient(_SshCredentials.Host, _SshCredentials.Login, _SshCredentials.Password))
                {
                    int expectedCommentsAndEmptryLinesCount = 0;
                    SftpClient.Connect();
                    using (Stream fileStream = File.OpenRead(DataSetsDirectory + "FileWithCode.txt"))
                    {
                        SftpClient.UploadFile(fileStream, "./FileWithCode.txt", canOverride: true);
                    }

                    SshClient.Connect();
                    using (var cmd = SshClient.CreateCommand($"cat FileWithCode.txt | sed '/^#[^!].*/d; /^$/d' | grep -c -E '(^#[^!].*|^$)'"))
                    {
                        cmd.Execute();
                        string cmdOutput = cmd.Result;
                        SftpClient.DeleteFile("./FileWithCode.txt");
                        SftpClient.Disconnect();
                        SshClient.Disconnect();
                        Assert.AreEqual(expectedCommentsAndEmptryLinesCount, Convert.ToInt32(cmdOutput));
                    }
                }
            }
        }
示例#8
0
        /// <summary>
        /// Delete a test folder on a server
        /// </summary>
        /// <param name="serverName">The server to connect to</param>
        /// <param name="userName">The user to log into</param>
        /// <param name="password">The password of the user</param>
        /// <param name="folderName">The name of the test folder to delete</param>
        public static void DeleteFiles(string serverName, string userName, string password, string folderName)
        {
            using (SftpClient client = new SftpClient("serverName", userName, password))
            {
                client.Connect();

                // cd TestDir
                if (!client.Exists("TestDir"))
                {
                    return;
                }
                client.ChangeDirectory("TestDir");

                // Delete folder
                if (!string.IsNullOrWhiteSpace(folderName) && client.Exists(folderName))
                {
                    // client.DeleteDirectory is not recursive, so have to go in and delete every file first
                    Parallel.ForEach(client.ListDirectory(folderName), k =>
                    {
                        try
                        {
                            client.DeleteFile(k.FullName);
                        }
                        // Catch delete failures coming from trying to delete './' or '../'
                        catch (SshException) { }
                    });

                    client.DeleteDirectory(folderName);
                }

                client.Disconnect();
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="file">Should take the form \server\dirx\...\filename</param>
        public override void DeleteFile(string file)
        {
            SftpClient conn = null;

            try
            {
                conn = OpenClient(file);

                file = AdjustPath(conn.ConnectionInfo.Host, file);

                if (conn.Exists(file))
                {
                    conn.DeleteFile(file);
                }
            }
            catch (Exception ex)
            {
                string exmsg = "Connection is null.";

                if (conn != null)
                {
                    exmsg = "WorkingDirectory: " + conn.WorkingDirectory + ", File: " + file;
                }

                DisposeClient(conn);
                conn = null;

                throw new Exception(exmsg, ex);
            }
            finally
            {
                RecycleClient(conn);
            }
        }
示例#10
0
        public void Delete(IEnumerable <FileInfo> targetFiles)
        {
            var target = (FromSettings)_channelSettings;

            var info = target.AsConnectionInfo();

            using (SftpClient client = new SftpClient(info))
            {
                client.Connect();

                if (client.Exists(target.Path))
                {
                    foreach (var file in targetFiles)
                    {
                        var filePath = Path.Combine(target.Path, file.Name);

                        client.DeleteFile(filePath);
                    }
                }
                else
                {
                    throw new Renci.SshNet.Common.SftpPathNotFoundException($"{target.Path}");
                }
            }
        }
示例#11
0
        /// <summary>
        /// Deletes the directory recursively.
        /// </summary>
        /// <param name="remoteDirectory">The remote directory.</param>
        public static void DeleteDirectoryRecursive(string remoteDirectory, SftpClient Client)
        {
            if (!Client.Exists(remoteDirectory))
            {
                return;
            }

            foreach (var file in Client.ListDirectory(remoteDirectory))
            {
                if (file.Name.Equals(".") || file.Name.Equals(".."))
                {
                    continue;
                }

                if (file.IsDirectory)
                {
                    DeleteDirectoryRecursive(file.FullName, Client);
                }
                else
                {
                    Client.DeleteFile(file.FullName);
                }
            }

            Client.DeleteDirectory(remoteDirectory);
        }
 public void Test_Sftp_DeleteFile_Null()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.DeleteFile(null);
     }
 }
示例#13
0
        public void SftpClient_AwkTableFilterManagers_ResultTableShouldContainAllManagers()
        {
            using (var SftpClient = new SftpClient(_SshCredentials.Host, _SshCredentials.Login, _SshCredentials.Password))
            {
                using (var SshClient = new SshClient(_SshCredentials.Host, _SshCredentials.Login, _SshCredentials.Password))
                {
                    int expectedTotalManagersCount = 3;
                    SftpClient.Connect();
                    using (Stream fileStream = File.OpenRead(DataSetsDirectory + "DataTable.txt"))
                    {
                        SftpClient.UploadFile(fileStream, "./DataTable.txt", canOverride: true);
                    }

                    SshClient.Connect();
                    using (var cmd = SshClient.CreateCommand("cat DataTable.txt | awk '/manager/ {print}' | grep -c 'manager'"))
                    {
                        cmd.Execute();
                        string cmdOutput = cmd.Result;
                        SftpClient.DeleteFile("./DataTable.txt");
                        SftpClient.Disconnect();
                        SshClient.Disconnect();
                        Assert.AreEqual(expectedTotalManagersCount, Convert.ToInt32(cmdOutput));
                    }
                }
            }
        }
示例#14
0
        protected override void Test(SftpAdapterConnectionParameters connectionParameters, SftpAdapterProcessorParameters processorParameters)
        {
            var fileName       = Guid.NewGuid().ToString();
            var folder         = string.IsNullOrWhiteSpace(connectionParameters.RootFolder) ? (processorParameters.SubFolder ?? "") : Path.Combine(connectionParameters.RootFolder, processorParameters.SubFolder ?? "");
            var connectionInfo = connectionParameters.CreateConnectionInfo();

            using (var client = new SftpClient(connectionInfo))
            {
                client.Connect();
                var    stream = new MemoryStream();
                byte[] fileContents;
                stream.Position = 0;
                using (MemoryStream ms = new MemoryStream())
                {
                    stream.CopyTo(ms);
                    fileContents = ms.ToArray();
                }

                client.WriteAllBytes(Path.Combine(folder, fileName), fileContents);
            }
            using (var client = new SftpClient(connectionInfo))
            {
                client.Connect();
                client.DeleteFile(Path.Combine(folder, fileName));
            }
        }
示例#15
0
        private void BUT_clearlogs_Click(object sender, EventArgs e)
        {
            if (CustomMessageBox.Show(LogStrings.Confirmation, "sure", MessageBoxButtons.YesNo) ==
                (int)System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    SftpClient sshclient = new SftpClient(_connectionInfo);
                    sshclient.Connect();

                    foreach (var logEntry in logEntries)
                    {
                        sshclient.DeleteFile(logEntry.FullName);
                    }

                    sshclient.Disconnect();

                    AppendSerialLog(LogStrings.EraseComplete);
                    status = SerialStatus.Done;
                    CHK_logs.Items.Clear();
                }
                catch (Exception ex)
                {
                    CustomMessageBox.Show(ex.Message, Strings.ERROR);
                }
            }
        }
示例#16
0
        public static void DeleteFile(string localFile, string host, string username, string password)
        {
            FileInfo f          = new FileInfo(localFile);
            string   uploadfile = f.FullName;

            Console.WriteLine(f.Name);
            Console.WriteLine("deletefile: " + uploadfile + "\r\n");

            //Passing the sftp host without the "sftp://"
            var client = new SftpClient(host, username, password);

            client.Connect();
            if (client.IsConnected)
            {
                var fileStream = new FileStream(uploadfile, FileMode.Open);
                if (fileStream != null)
                {
                    //If you have a folder located at sftp://ftp.example.com/share
                    //then you can add this like:
                    client.DeleteFile("/root/" + f.Name);
                    client.Disconnect();
                    client.Dispose();
                }
                fileStream.Close();
            }
        }
 public void Test_Sftp_DeleteFile_Null()
 {
     using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
     {
         sftp.DeleteFile(null);
     }
 }
 /// <inheritdoc/>
 public void DeleteFile(String fileName)
 {
     HandleExceptions(() =>
     {
         _sftpClient.DeleteFile(fileName);
     }, fileName);
 }
示例#19
0
        //// They want us to delete the files that we've successfully processed. Use this.
        public bool DeleteFile(string file, string diretorioLocal, IntegracaoInfos sftpInfo)
        {
            bool success = true;

            try
            {
                SftpClient tmpClient;
                if (sftpInfo.Senha != "")
                {
                    tmpClient = new SftpClient(sftpInfo.HostURI, sftpInfo.Usuario, sftpInfo.Senha);
                }
                else
                {
                    var sftpModelShared = new SftpModel(sftpInfo.DiretorioInspecaoLocal, sftpInfo.HostURI, sftpInfo.Usuario,
                                                        sftpInfo.PrivateKey, sftpInfo.Senha);
                    tmpClient = new SftpClient(sftpModelShared.HostURI, sftpModelShared.Usuario, sftpModelShared.PrivateKey);
                }

                // was new SftpClient(this.HostURI, this.UserName, this.PrivateKey)
                using (SftpClient client = tmpClient)
                {
                    client.Connect();

                    client.DeleteFile(diretorioLocal + file);


                    client.Disconnect();
                }
            }
            catch
            {
                success = false;
            }
            return(success);
        }
示例#20
0
        public void SftpClient_SedReplaceWordVirusToKasperskyInFile_FileShouldContain3KasperskyWords()
        {
            using (var SftpClient = new SftpClient(_SshCredentials.Host, _SshCredentials.Login, _SshCredentials.Password))
            {
                using (var SshClient = new SshClient(_SshCredentials.Host, _SshCredentials.Login, _SshCredentials.Password))
                {
                    int expectedKasperskyWordsCount = 3;
                    SftpClient.Connect();
                    using (Stream fileStream = File.OpenRead(DataSetsDirectory + "VirusToKaspersky.txt"))
                    {
                        SftpClient.UploadFile(fileStream, "./VirusToKaspersky.txt", canOverride: true);
                    }

                    SshClient.Connect();
                    using (var cmd = SshClient.CreateCommand($"cat VirusToKaspersky.txt | sed 's/virus/kaspersky/g' | grep -c 'kaspersky'"))
                    {
                        cmd.Execute();
                        string cmdOutput = cmd.Result;
                        SftpClient.DeleteFile("./VirusToKaspersky.txt");
                        SftpClient.Disconnect();
                        SshClient.Disconnect();
                        Assert.AreEqual(expectedKasperskyWordsCount, Convert.ToInt32(cmdOutput));
                    }
                }
            }
        }
        public void SendFile(string name, string fullPath)
        {
            if (File.Exists(fullPath))
            {
                using (var sftp = new SftpClient(_settings.SftpRemote.Address, _settings.SftpRemote.Username, _settings.SftpRemote.Password)) {
                    _logger.LogInformation("Connecting to Sftp Server");
                    sftp.Connect();

                    _logger.LogInformation("Creating FileStream object to stream a file");
                    using (var uplfileStream = System.IO.File.OpenRead(fullPath)) {
                        if (!string.IsNullOrEmpty(_settings.SftpRemote.RemoteDirectory))
                        {
                            sftp.ChangeDirectory(_settings.SftpRemote.RemoteDirectory);
                        }

                        if (sftp.Exists(name))
                        {
                            sftp.DeleteFile(name);
                        }

                        sftp.UploadFile(uplfileStream, name, true);
                    }
                    sftp.Dispose();
                }
            }
            else
            {
                _logger.LogWarning($"File Not Found : {name}.  Ensure the path, {fullPath}, is correct.");
            }
        }
示例#22
0
        public void get()
        {
            try
            {
                client.Connect();
            }
            catch (Exception e)
            {
                successfulConnection = false;
                log.append("Unable to download files from FTP Server: Error connecting to FTP site");
            }

            if (successfulConnection)
            {
                var files = client.ListDirectory(remoteDirectory);

                foreach (var file in files)
                {
                    if ((file.Name.EndsWith(".ASC")))
                    {
                        string remoteFileName = file.Name;
                        using (Stream file1 = File.OpenWrite(getFiles + remoteFileName))
                        {
                            client.DownloadFile(remoteDirectory + remoteFileName, file1);
                            log.append("Downloaded file " + remoteFileName);
                            client.DeleteFile(remoteDirectory + remoteFileName);
                        }
                    }

                    else if ((file.Name.EndsWith(".csv")))
                    {
                        string remoteFileName = file.Name;


                        using (Stream file1 = File.OpenWrite(rejectDirectory + remoteFileName))
                        {
                            System.Diagnostics.Debug.WriteLine("testccc " + rejectDirectory + remoteFileName);
                            client.DownloadFile(remoteDirectory + remoteFileName, file1);
                            log.append("Downloaded file " + remoteFileName);
                            client.DeleteFile(remoteDirectory + remoteFileName);
                        }
                    }
                }
                //test
                client.Disconnect();
            }
        }
示例#23
0
 public void RemoveFile(string path)
 {
     if (!string.IsNullOrWhiteSpace(_rootPath))
     {
         path = LexicalPath.Combine(_rootPath, path);
     }
     _client.DeleteFile(path);
 }
示例#24
0
 public Task DeleteFile(string filePath)
 {
     return(HandleCommonExceptions(() => {
         _logger?.LogDebug($"DeleteFile('{filePath}')");
         _client.DeleteFile(filePath);
         _logger?.LogDebug($"DeleteFile('{filePath}'): done");
     }));
 }
示例#25
0
        /// <summary>
        /// Removes the remote SFTP file
        /// </summary>
        /// <param name="sftpClient"></param>
        /// <param name="sftpFile"></param>
        private void DeleteRemoteSftpFile(SftpClient sftpClient, SftpFile sftpFile)
        {
            _logger.LogInformation($"Deleting file {sftpFile.Name} from remote site");

            sftpClient.DeleteFile(sftpFile.FullName);

            _logger.LogInformation($"{sftpFile.Name} deleted");
        }
示例#26
0
        public void Upload(string topath)
        {
            sw.Close();
            //string topath = path; //+"/upload/"+entity+"/";
            if (!Directory.Exists(topath))
            {
                Directory.CreateDirectory(topath);
            }

            if (!File.Exists(topath + filename))
            {
                File.Move(path, topath + filename);
            }
            else
            {
                //File.Move(topath, backuppath + GuaLCOID + "-" + DateTime.Now.ToString("MMddyyyyhhmmss") + ".csv");
                File.Delete(topath + filename);
                File.Move(path, topath + filename);
                //File.Replace(path,topath,);
            }

            string servername = ConfigurationSettings.AppSettings["appserver"];
            string username   = ConfigurationSettings.AppSettings["username"];
            string password   = ConfigurationSettings.AppSettings["password"];

            ConnectionInfo connectionInfo = new PasswordConnectionInfo(servername, 22, username, password);

            try
            {
                using (var client = new SftpClient(connectionInfo))
                {
                    //SftpClient
                    client.Connect();

                    using (var file = File.OpenRead(topath + filename))
                    {
                        //client.get
                        try
                        {
                            client.CreateDirectory("/var/media/files/" + entity + "/");
                        }
                        catch { }
                        try
                        {
                            client.DeleteFile("/var/media/files/" + entity + "/" + filename);
                        }
                        catch { }
                        client.UploadFile(file, "/var/media/files/" + entity + "/" + filename);
                        cmd.WriteLine("Upload Complete.");
                    }
                    //client.
                }
            }
            catch (Exception e)
            {
                cmd.WriteLine("Upload failed : " + e.Message, Info.Error);
            }
        }
            public static SshWebResponse GetDeleteResponse(SftpClient client, string path)
            {
                var response = new SshWebResponse();

                if (client.Exists(path))
                {
                    client.DeleteFile(path);
                }

                path = path.TrimStart('/');

                if (client.Exists(path))
                {
                    client.DeleteFile(path);
                }

                return(response);
            }
示例#28
0
        protected void MustDeleteFileCore()
        {
            string methodName    = GetCurrentMethod();
            string dummyFileName = methodName + "_dummy.txt";

            Utils.CreateDummyFile(MockData.SftpDataFolder, dummyFileName, cleanFolder: false);
            SftpClient.DeleteFile(dummyFileName);
            Assert.False(File.Exists(Path.Combine(MockData.SftpDataFolder, dummyFileName)));
        }
示例#29
0
 public async Task<bool> Delete(string RemotePath, SftpClient client = null)
 {
     try {
         client = client ?? await this.Connect();
         client.DeleteFile(RemotePath);
         return true;
     }
     catch{ return false; }
 }
示例#30
0
        public void DeleteFile(string filePath)
        {
            using SftpClient sftpClient = CreateSftpClient();

            sftpClient.Connect();

            sftpClient.DeleteFile(filePath);

            sftpClient.Disconnect();
        }
        public void DeleteOnRemote()
        {
            var connectionInfo = _connectionInfo.CreateConnectionInfo();

            using (var client = new SftpClient(connectionInfo))
            {
                client.Connect();
                client.DeleteFile(Path.Combine(_path, Name));
            }
        }
示例#32
0
        public void Test_Sftp_Upload_And_Download_1MB_File()
        {
            RemoveAllFiles();

            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                string uploadedFileName = Path.GetTempFileName();
                string remoteFileName = Path.GetRandomFileName();

                this.CreateTestFile(uploadedFileName, 1);

                //  Calculate has value
                var uploadedHash = CalculateMD5(uploadedFileName);

                using (var file = File.OpenRead(uploadedFileName))
                {
                    sftp.UploadFile(file, remoteFileName);
                }

                string downloadedFileName = Path.GetTempFileName();

                using (var file = File.OpenWrite(downloadedFileName))
                {
                    sftp.DownloadFile(remoteFileName, file);
                }

                var downloadedHash = CalculateMD5(downloadedFileName);

                sftp.DeleteFile(remoteFileName);

                File.Delete(uploadedFileName);
                File.Delete(downloadedFileName);

                sftp.Disconnect();

                Assert.AreEqual(uploadedHash, downloadedHash);
            }
        }
示例#33
0
        public void Test_Sftp_Multiple_Async_Upload_And_Download_10Files_5MB_Each()
        {
            var maxFiles = 10;
            var maxSize = 5;

            using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
            {
                sftp.Connect();

                var testInfoList = new Dictionary<string, TestInfo>();

                for (int i = 0; i < maxFiles; i++)
                {
                    var testInfo = new TestInfo();
                    testInfo.UploadedFileName = Path.GetTempFileName();
                    testInfo.DownloadedFileName = Path.GetTempFileName();
                    testInfo.RemoteFileName = Path.GetRandomFileName();

                    this.CreateTestFile(testInfo.UploadedFileName, maxSize);

                    //  Calculate hash value
                    testInfo.UploadedHash = CalculateMD5(testInfo.UploadedFileName);

                    testInfoList.Add(testInfo.RemoteFileName, testInfo);
                }

                var uploadWaitHandles = new List<WaitHandle>();

                //  Start file uploads
                foreach (var remoteFile in testInfoList.Keys)
                {
                    var testInfo = testInfoList[remoteFile];
                    testInfo.UploadedFile = File.OpenRead(testInfo.UploadedFileName);

                    testInfo.UploadResult = sftp.BeginUploadFile(testInfo.UploadedFile,
                        remoteFile,
                        null,
                        null) as SftpUploadAsyncResult;

                    uploadWaitHandles.Add(testInfo.UploadResult.AsyncWaitHandle);
                }

                //  Wait for upload to finish
                bool uploadCompleted = false;
                while (!uploadCompleted)
                {
                    //  Assume upload completed
                    uploadCompleted = true;

                    foreach (var testInfo in testInfoList.Values)
                    {
                        var sftpResult = testInfo.UploadResult;

                        if (!testInfo.UploadResult.IsCompleted)
                        {
                            uploadCompleted = false;
                        }
                    }
                    Thread.Sleep(500);
                }

                //  End file uploads
                foreach (var remoteFile in testInfoList.Keys)
                {
                    var testInfo = testInfoList[remoteFile];

                    sftp.EndUploadFile(testInfo.UploadResult);
                    testInfo.UploadedFile.Dispose();
                }

                //  Start file downloads

                var downloadWaitHandles = new List<WaitHandle>();

                foreach (var remoteFile in testInfoList.Keys)
                {
                    var testInfo = testInfoList[remoteFile];
                    testInfo.DownloadedFile = File.OpenWrite(testInfo.DownloadedFileName);
                    testInfo.DownloadResult = sftp.BeginDownloadFile(remoteFile,
                        testInfo.DownloadedFile,
                        null,
                        null) as SftpDownloadAsyncResult;

                    downloadWaitHandles.Add(testInfo.DownloadResult.AsyncWaitHandle);
                }

                //  Wait for download to finish
                bool downloadCompleted = false;
                while (!downloadCompleted)
                {
                    //  Assume download completed
                    downloadCompleted = true;

                    foreach (var testInfo in testInfoList.Values)
                    {
                        var sftpResult = testInfo.DownloadResult;

                        if (!testInfo.DownloadResult.IsCompleted)
                        {
                            downloadCompleted = false;
                        }
                    }
                    Thread.Sleep(500);
                }

                var hashMatches = true;
                var uploadDownloadSizeOk = true;

                //  End file downloads
                foreach (var remoteFile in testInfoList.Keys)
                {
                    var testInfo = testInfoList[remoteFile];

                    sftp.EndDownloadFile(testInfo.DownloadResult);

                    testInfo.DownloadedFile.Dispose();

                    testInfo.DownloadedHash = CalculateMD5(testInfo.DownloadedFileName);

                    if (!(testInfo.UploadResult.UploadedBytes > 0 && testInfo.DownloadResult.DownloadedBytes > 0 && testInfo.DownloadResult.DownloadedBytes == testInfo.UploadResult.UploadedBytes))
                    {
                        uploadDownloadSizeOk = false;
                    }

                    if (!testInfo.DownloadedHash.Equals(testInfo.UploadedHash))
                    {
                        hashMatches = false;
                    }
                }

                //  Clean up after test
                foreach (var remoteFile in testInfoList.Keys)
                {
                    var testInfo = testInfoList[remoteFile];

                    sftp.DeleteFile(remoteFile);

                    File.Delete(testInfo.UploadedFileName);
                    File.Delete(testInfo.DownloadedFileName);
                }

                sftp.Disconnect();

                Assert.IsTrue(hashMatches, "Hash does not match");
                Assert.IsTrue(uploadDownloadSizeOk, "Uploaded and downloaded bytes does not match");
            }
        }
示例#34
0
 public void DeleteFileTest()
 {
     ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value
     SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value
     string path = string.Empty; // TODO: Initialize to an appropriate value
     target.DeleteFile(path);
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }