FtpWebRequest ProtocolViolationException

77 Views Asked by At

Trying to create an ftp download async function with IProgress and cancelation token, but I'm getting a "ProtocolViolationException: Operation is not valid due to the current state of the object" on GetRequestStreamAsync() function

I was using this as an inspiration upload async with IProgress and cancelation token

        public async Task DownloadWithProgressAsync(string remoteFilepath, string localFilepath, IProgress<decimal> progress, CancellationToken token)
        {
            const int bufferSize = 128 * 1024;  // 128kb buffer
            progress.Report(0m);

            var remoteUri = new Uri(_baseUrl + remoteFilepath);
            Debug.Log($"Download\nuri: {remoteUri}");

            var request = (FtpWebRequest)WebRequest.CreateDefault(remoteUri);
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new NetworkCredential(_username, _password);

            token.ThrowIfCancellationRequested();

            using (var fileStream = new FileStream(localFilepath, FileMode.OpenOrCreate, FileAccess.Write,
                FileShare.Write, bufferSize, true))
            {
                using (var ftpStream = await request.GetRequestStreamAsync())
                {
                    var buffer = new byte[bufferSize];
                    int read;
                    while ((read = await ftpStream.ReadAsync(buffer, 0, buffer.Length, token) ) > 0)
                    {
                        await fileStream.WriteAsync(buffer, 0, read, token);
                        var percent = (decimal)ftpStream.Position / ftpStream.Length;
                        progress.Report(percent);
                    }
                }
            }

            var response = (FtpWebResponse)await request.GetResponseAsync();
            var success = (int)response.StatusCode >= 200 && (int)response.StatusCode < 300;
            response.Close();
            if (!success)
                throw new Exception(response.StatusDescription);
        }
0

There are 0 best solutions below