DeleteFile() public method

Deletes remote file specified by path.
is null or contains only whitespace characters. Client is not connected. was not found on the remote host. Permission to delete the file was denied by the remote host. -or- A SSH command was denied by the server. A SSH error where is the message from the remote host. The method was called after the client was disposed.
public DeleteFile ( string path ) : void
path string File to be deleted path.
return void
Example #1
0
        /// <inheritdoc />
        public Task UploadFileToServerAsync(Stream stream, string basePath, string fileName, bool overwrite = false)
        {
            if (String.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException(nameof(fileName));
            }
            if (String.IsNullOrWhiteSpace(basePath))
            {
                throw new ArgumentNullException(nameof(basePath));
            }

            if (stream == null)
            {
                throw new ArgumentNullException(fileName);
            }
            if (stream.Length == 0)
            {
                throw new ArgumentException(LNG.SftpClient_CanNotBeEmpty, nameof(stream));
            }

            return(_retryAsyncPolicy.ExecuteAsync(() =>
            {
                EnsureConnected();

                var filePath = GetFileFullPath(basePath, fileName);

                if (_sftpClient.Exists(filePath))
                {
                    // Check file size.
                    var attributes = _sftpClient.GetAttributes(filePath);
                    if (attributes.Size == stream.Length)
                    {
                        // Size is equal. Assume that files are equal. No need to upload.
                        _logger.LogWarning(String.Format(LNG.SftpClient_SameFileAlreadyExists, fileName));
                        return Task.CompletedTask;
                    }

                    if (overwrite)
                    {
                        // can overwrite, so delete file
                        _logger.LogWarning(String.Format(
                                               LNG.SftpClient_Overwriting,
                                               fileName,
                                               attributes.Size,
                                               stream.Length));
                        _sftpClient.DeleteFile(filePath);
                    }
                    else
                    {
                        // can't overwrite, it's error
                        throw new SshException(
                            String.Format(
                                LNG.SftpClient_DifferentFileAlreadyExists,
                                fileName,
                                attributes.Size,
                                stream.Length));
                    }
                }

                var sftpDirectory = Path.GetDirectoryName(filePath)
                                    ?.Replace(@"\", "/") // windows-linux compatibility
                                    ?? throw new InvalidOperationException("File path can't be mull");

                if (!_sftpClient.Exists(sftpDirectory))
                {
                    CreateDirectoryRecursively(sftpDirectory);
                }

                //TODO #3 check it, I think we don't need it here
                // we need to set position to start because temp stream can be used in another places
                stream.Position = 0;

                return Task.Factory.FromAsync(
                    _sftpClient.BeginUploadFile(
                        stream,
                        filePath,
                        false,
                        null,
                        null),
                    _sftpClient.EndUploadFile);
            }));
        }
Example #2
-1
        private bool Sftp(string server, int port, bool passive, string username, string password, string filename, int counter, byte[] contents, out string error, bool rename)
        {
            bool failed = false;
            error = "";
            try
            {
                int i = 0;
                filename = filename.Replace("{C}", counter.ToString(CultureInfo.InvariantCulture));
                if (rename)
                    filename += ".tmp";

                while (filename.IndexOf("{", StringComparison.Ordinal) != -1 && i < 20)
                {
                    filename = String.Format(CultureInfo.InvariantCulture, filename, Helper.Now);
                    i++;
                }

                var methods = new List<AuthenticationMethod> { new PasswordAuthenticationMethod(username, password) };

                var con = new ConnectionInfo(server, port, username, methods.ToArray());
                using (var client = new SftpClient(con))
                {
                    client.Connect();

                    var filepath = filename.Trim('/').Split('/');
                    var path = "";
                    for (var iDir = 0; iDir < filepath.Length - 1; iDir++)
                    {
                        path += filepath[iDir] + "/";
                        try
                        {
                            client.CreateDirectory(path);
                        }
                        catch
                        {
                            //directory exists
                        }
                    }
                    if (path != "")
                    {
                        client.ChangeDirectory(path);
                    }

                    filename = filepath[filepath.Length - 1];

                    using (Stream stream = new MemoryStream(contents))
                    {
                        client.UploadFile(stream, filename);
                        if (rename)
                        {
                            try
                            {
                                //delete target file?
                                client.DeleteFile(filename.Substring(0, filename.Length - 4));
                            }
                            catch (Exception)
                            {
                            }
                            client.RenameFile(filename, filename.Substring(0, filename.Length - 4));
                        }
                    }

                    client.Disconnect();
                }

                MainForm.LogMessageToFile("SFTP'd " + filename + " to " + server + " port " + port, "SFTP");
            }
            catch (Exception ex)
            {
                error = ex.Message;
                failed = true;
            }
            return !failed;
        }