FluentFTP icon indicating copy to clipboard operation
FluentFTP copied to clipboard

Timed out trying to read data from the socket stream!

Open JWcodeDev opened this issue 7 years ago • 26 comments

NOTE FROM ADMIN:

This should be fixed in 29.0.0 and onwards. But if you still have this issue, please add your post below instead of creating duplicate issues!

Thanks.


I am not able to upload a file to a FTPS site. I keep receiving the following error. If the file exists it will delete the file from the FTP but it will not upload the new file.

{"Timed out trying to read data from the socket stream!"}

Here is my code:

        FtpClient client = new FtpClient("ftp", "user", "pwd");

        client.DataConnectionType = FtpDataConnectionType.PASV;
        client.EncryptionMode = FtpEncryptionMode.Explicit;
        client.SslProtocols = System.Security.Authentication.SslProtocols.Tls11;
        client.ValidateCertificate += new FtpSslValidation(OnValidateCertificate);
        client.Encoding = System.Text.Encoding.ASCII;

        client.UploadFile(@"C:\Test\Test.txt", "/archive/Test.txt", FtpExists.Overwrite, true, FtpVerify.Retry);

         client.Disconnect();

It errors out on the client.UploadFile line.

Seems it is in the GetRequestStream(). Not sure how to over come this error.

Thanks,

JW

JWcodeDev avatar Jun 14 '17 18:06 JWcodeDev

Please send full logs in order for us to debug. Read the FAQ on how to print or save logs to a file.

robinrodricks avatar Jun 15 '17 07:06 robinrodricks

Thanks for the Response.

Here are the logs:

# UploadFile("C:\Test\Test.txt", "/Test.txt", Overwrite, True, None)

# FileExists("/Test.txt")

# Connect()
Status:   Connecting to ***:21
Response: 220 Welcome To  Solutions.  All traffic is monitored and scanned.
Response: 220-Microsoft FTP Service
Command:  AUTH TLS
Response: 234 AUTH command ok. Expecting TLS Negotiation.
Status:   FTPS Authentication Successful
Status:   Time to activate encryption: 0h 0m 0s.  Total Seconds: 0.3145793.
Command:  USER ***
Response: 331 Password required
Command:  PASSS ***
Response: 230 User logged in.
Command:  PBSZ 0
Response: 200 PBSZ command successful.
Command:  PROT P
Response: 200 PROT command successful.
Command:  FEAT
Response: 211 END
Response: 211-Extended features supported:
Response: LANG EN*
Response: UTF8
Response: AUTH TLS;TLS-C;SSL;TLS-P;
Response: PBSZ
Response: PROT C;P;
Response: CCC
Response: HOST
Response: SIZE
Response: MDTM
Response: REST STREAM
Status:   Text encoding: System.Text.ASCIIEncoding
Command:  SYST
Response: 215 Windows_NT
Status:   Auto-detected Windows listing parser
Command:  SIZE /Test.txt
Response: 550 The system cannot find the file specified. 

# DirectoryExists("")

# OpenWrite("/Test.txt", Binary)
Command:  TYPE I
Response: 200 Type set to I.

# GetFileSize("/Test.txt")
Command:  SIZE /Test.txt
Response: 550 The system cannot find the file specified. 

# OpenPassiveDataStream(PASV, "STOR /Test.txt", 0)
Command:  PASV
Response: 227 Entering Passive Mode (00,00,00,00,153,114).
Status:   Connecting to ***:39282
Command:  STOR /Test.txt

UnhandledExceptionHandler - Error while uploading the file to the server. See InnerException for more info..
   at FluentFTP.FtpClient.UploadFileInternal(Stream fileData, String remotePath, Boolean createRemoteDir, FtpExists existsMode, Boolean fileExists, Boolean fileExistsKnown)
   at FluentFTP.FtpClient.UploadFileFromFile(String localPath, String remotePath, Boolean createRemoteDir, FtpExists existsMode, Boolean fileExists, Boolean fileExistsKnown, FtpVerify verifyOptions)
   at FluentFTP.FtpClient.UploadFile(String localPath, String remotePath, FtpExists existsMode, Boolean createRemoteDir, FtpVerify verifyOptions)
   at FTP2.Program.Main(String[] args) in c:\AAA_Projects\FTP2\FTP2\Program.cs:line 55
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Inner Exception:

{"Timed out trying to read data from the socket stream!"}

JWcodeDev avatar Jun 15 '17 14:06 JWcodeDev

When you use FileZilla does it work? Can you do this to verify and also paste the FileZilla logs here so I can compare what it does different?

robinrodricks avatar Jun 15 '17 14:06 robinrodricks

I actually can't get a directory listing through FileZilla but I can through other FTP Clients.

JWcodeDev avatar Jun 15 '17 15:06 JWcodeDev

Okay use another client but paste the FTP logs so we can compare with our library.

robinrodricks avatar Jun 18 '17 08:06 robinrodricks

Here is the log from Core FTP with a successful file transfer.

Resolving ***...  
Connect socket #1488 to ***, port 21...
220-Microsoft FTP Service  
220-Microsoft FTP Service  
220 Welcome To Solutions.  All traffic is monitored and scanned.  
AUTH TLS  
234 AUTH command ok. Expecting TLS Negotiation.  
TLSv1.2, cipher TLSv1/SSLv3 (ECDHE-RSA-AES256-SHA384) - 256 bit
USER ***  
331 Password required  
PASS **********  
230 User logged in.  
SYST  
215 Windows_NT  
Keep alive off...
PWD  
257 "/" is current directory.  
PBSZ 0  
200 PBSZ command successful.  
PROT P  
200 PROT command successful.  
PASV  
227 Entering Passive Mode (***,196,23).  
LIST  
Connect socket #1292 to ***, port 50199...
150 Opening ASCII mode data connection.  
TLSv1.2, cipher TLSv1/SSLv3 (ECDHE-RSA-AES256-SHA384) - 256 bit
226 Transfer complete.  
Transferred 48 bytes in 0.017 seconds  
PWD  
257 "/" is current directory.  
TYPE A  
200 Type set to A.  
PASV  
227 Entering Passive Mode (***,196,24).  
STOR Leads_20170619.csv  
Connect socket #1440 to ***, port 50200...
TLSv1.2, cipher TLSv1/SSLv3 (ECDHE-RSA-AES256-SHA384) - 256 bit
150 Opening ASCII mode data connection.  
226 Transfer complete.  
Leads_20170619.csv - 31967 bytes transferred in 0 seconds  
MDTM 20170619124726 Leads_20170619.csv  
213 20170619124726  
Transfer time: 00:00:01  

JWcodeDev avatar Jun 19 '17 11:06 JWcodeDev

This is very similar to my issue #124, not only because of the same error message ("Timed out trying to read data from the socket stream!") but also because of ASCII vs Binary mode. In your example of a successful transfer, the type is set to ASCII prior to the upload:

TYPE A  
200 Type set to A.  
PASV  
227 Entering Passive Mode (***,196,24).  
STOR Leads_20170619.csv 

In your logs of the failed transfer on the other hand, the data mode is set to Binary prior to the transfer:

# OpenWrite("/Test.txt", Binary)
Command:  TYPE I
Response: 200 Type set to I.

# GetFileSize("/Test.txt")
Command:  SIZE /Test.txt
Response: 550 The system cannot find the file specified. 

# OpenPassiveDataStream(PASV, "STOR /Test.txt", 0)
Command:  PASV
Response: 227 Entering Passive Mode (00,00,00,00,153,114).
Status:   Connecting to ***:39282
Command:  STOR /Test.txt

molekamp avatar Jun 20 '17 20:06 molekamp

@molekamp Amazing that you two have a similar error and thanks for debugging this use case. I will try to support ASCII transfers for the high level APIs too.

robinrodricks avatar Jun 21 '17 08:06 robinrodricks

@JWcodeDev

Can you try this beta version, which has new properties (UploadDataType, DownloadDataType) that control usage of the ASCII/Binary mode with the high level API.

Specifically in your case set both to use ASCII mode and that should mimic the behavior by CoreFTP.

robinrodricks avatar Jun 22 '17 16:06 robinrodricks

I had same issue here. With Winscp works normally. After some hours and retries i've found that change

DataConnectionType = FtpDataConnectionType.EPSV, the problem vanishes ! :)

The choice the connection type involves examinate some server response messages. In my case, Server response (Thanks FluentFTP Trace)

Connect()

Status: Connecting to *********** Response: 220 Bs As Argentina Response: 220-FileZilla Server 0.9.60 beta (sensible information) Response: 220-Si no cuenta con la autorizacion, por favor desconecte su sesion Response: 220-inmediatamente! Response: 220- Command: PASS *** Response: 230 Logged on Command: FEAT Response: 211 End Response: 211-Features: Response: MDTM Response: REST STREAM Response: SIZE Response: MLST type*;size*;modify*; Response: MLSD Response: AUTH SSL Response: AUTH TLS Response: PROT Response: PBSZ Response: UTF8 Response: CLNT Response: MFMT Response: EPSV Response: EPRT Status: Text encoding: System.Text.ASCIIEncoding Command: SYST Response: 215 UNIX emulated by FileZilla Status: Auto-detected UNIX listing parser

greydmar avatar Jan 11 '18 19:01 greydmar

Yeah. DataConnectionType = FtpDataConnectionType.EPSV did the trick. Now I'm able to upload large files.

The C# intellisense recommends this setting. So why we have to set it?

fschwengsbier avatar Jul 25 '18 23:07 fschwengsbier

@fschwengsbier Not sure why intellisense recommends it. By design of the original author, the library first tries EPSV then passive then gives up. Not sure why its not working in your case.

robinrodricks avatar Jan 31 '19 04:01 robinrodricks

@fschwengsbier

Yeah. DataConnectionType = FtpDataConnectionType.EPSV did the trick. Now I'm able to upload large files.

The C# intellisense recommends this setting. So why do we have to set it?

That worked for me too after trying almost everything else. Thanks!

Filezilla working on my case, and the bug only appeared while uploading to some FTP servers but not all.

Sithdown avatar Feb 09 '19 00:02 Sithdown

Hi, have any news? I've updates de dll version to latest and get same error.

Upload big file "sql.bak" is OK, but return error in my code:

Message --> Timed out trying to read data from the socket stream!

In this example i upload 2 files, the first (small) upload and check success, but second (big) upload ok but not return success.

If i tried only 1 (big) still the same problem.

`

Connect()

Status: Connecting to :21 Response: 220 FileZilla Backup Server (0.9.60) Command: USER *** Response: 331 Password required for user Command: PASS *** Response: 230 Logged on Command: FEAT Response: 211 End Response: 211-Features: Response: MDTM Response: REST STREAM Response: SIZE Response: MODE Z Response: MLST type;size;modify; Response: MLSD Response: AUTH SSL Response: AUTH TLS Response: PROT Response: PBSZ Response: UTF8 Response: CLNT Response: MFMT Response: EPSV Response: EPRT Status: Text encoding: System.Text.UTF8Encoding Command: OPTS UTF8 ON Response: 202 UTF8 mode is always enabled. No need to send this command. Command: SYST Response: 215 UNIX emulated by FileZilla Status: Auto-detected UNIX listing parser

UploadFile("C:\sql.bak.md5", "/sql.bak.md5", NoCheck, False, None)

OpenWrite("/sql.bak.md5", Binary)

Command: TYPE I Response: 200 Type set to I

GetFileSize("/sql.bak.md5")

Command: SIZE /sql.bak.md5 Response: 550 File not found

OpenPassiveDataStream(EPSV, "STOR /sql.bak.md5", 0)

Command: EPSV Response: 229 Entering Extended Passive Mode (|||55570|) Status: Connecting to ***:55570 Command: STOR /sql.bak.md5 Response: 150 Opening data channel for file upload to server of "/sql.bak.md5" Status: Disposing FtpSocketStream... Response: 226 Successfully transferred "/sql.bak.md5"

UploadFile("C:\sql.bak", "/sql.bak", NoCheck, False, None)

OpenWrite("/sql.bak", Binary)

GetFileSize("/sql.bak")

Command: SIZE /sql.bak Response: 550 File not found

OpenPassiveDataStream(EPSV, "STOR /sql.bak", 0)

Command: EPSV Response: 229 Entering Extended Passive Mode (|||58001|) Status: Connecting to ***:58001 Command: STOR /sql.bak Response: 150 Opening data channel for file upload to server of "/sql.bak" Status: Disposing FtpSocketStream... Status: Testing connectivity using Socket.Poll()... Status: Disposing FtpSocketStream... Status: Disposing FtpSocketStream...

Dispose()

Status: Disposing FtpClient object... Status: Disposing FtpSocketStream...`

nicojmb avatar Jun 26 '19 14:06 nicojmb

I have been experiencing a similar issue. My process attempts to download a 3.2Gb file every 24 hours. The first attempt after a VM restart works, but subsequent attempts eventually receive:

There is stale data on the socket, maybe our connection timed out or you did not call GetReply(). Re-connecting...

I disabled the swap file on the VM, and it now works consistently.

aharkness avatar Aug 13 '19 14:08 aharkness

Just putting this here because I had the same error and it took me a while before I finally found a stackoverflow question that helped me solve this issue. I tried setting the DataConnectionMode with no luck. I was trying to connect to port 990 using Explicit EncryptionMode, which doesn't work. When connecting to port 990 you MUST use Implicit EncryptionMode. Credit: https://stackoverflow.com/a/47710332/2532817

tkburbidge avatar Sep 27 '19 22:09 tkburbidge

Fixed one of the causes of this issue in the latest : https://www.nuget.org/packages/FluentFTP/27.1.4

There were unnecessary TimeoutExceptions being thrown AFTER the file was fully uploaded/downloaded. These are now absorbed and don't cause any issue.

robinrodricks avatar Oct 08 '19 07:10 robinrodricks

FluentFTP.FtpException: Error while uploading the file to the server. See InnerException for more info. ---> System.TimeoutException: Timed out trying to read data from the socket stream! 在 FluentFTP.FtpSocketStream.Read(Byte[] buffer, Int32 offset, Int32 count) 在 FluentFTP.FtpSocketStream.ReadLine(Encoding encoding) 在 FluentFTP.FtpClient.GetReply() 在 FluentFTP.FtpClient.UploadFileInternal(Stream fileData, String remotePath, Boolean createRemoteDir, FtpExists existsMode, Boolean fileExists, Boolean fileExistsKnown, IProgress1 progress) --- 内部异常堆栈跟踪的结尾(inner Exception) --- 在 FluentFTP.FtpClient.UploadFileInternal(Stream fileData, String remotePath, Boolean createRemoteDir, FtpExists existsMode, Boolean fileExists, Boolean fileExistsKnown, IProgress1 progress) 在 FluentFTP.FtpClient.UploadFileFromFile(String localPath, String remotePath, Boolean createRemoteDir, FtpExists existsMode, Boolean fileExists, Boolean fileExistsKnown, FtpVerify verifyOptions, IProgress1 progress) 在 FluentFTP.FtpClient.UploadFile(String localPath, String remotePath, FtpExists existsMode, Boolean createRemoteDir, FtpVerify verifyOptions, IProgress1 progress)

FileZilla Success log: 状态: 正在连接IP 状态: 连接建立,等待欢迎消息... 状态: 不安全的服务器,不支持 FTP over TLS。 状态: 已登录 状态: 读取目录列表... 状态: 服务器发回了不可路由的地址。使用服务器地址代替。 状态: 列出“/”的目录成功 状态: 正在连接 IP 状态: 连接建立,等待欢迎消息... 状态: 不安全的服务器,不支持 FTP over TLS。 状态: 已登录 状态: 开始上传 N:\VideoTemp\3TP2019103116375201.mp4 状态: 服务器发回了不可路由的地址。使用服务器地址代替。 命令: STOR 3TP2019103116375201.mp4 响应: 150 Ok to send data. 错误: 20 秒后无活动,连接超时 错误: 传输了 3,526,631 字节 (用时50 秒)后文件传输失败 状态: 已从服务器断开 状态: 正在连接 ip 状态: 连接建立,等待欢迎消息... 状态: 不安全的服务器,不支持 FTP over TLS。 状态: 已登录 状态: 开始上传 N:\VideoTemp\3TP2019103116375201.mp4 状态: 读取“/”的目录列表... 状态: 服务器发回了不可路由的地址。使用服务器地址代替。 状态: 计算服务器时差... 状态: Timezone offset of server is 0 seconds. 状态: 服务器发回了不可路由的地址。使用服务器地址代替。 状态: 文件传输成功,传输了 1,031,703 字节 (用时40 秒) 状态: 读取“/”的目录列表... 状态: 服务器发回了不可路由的地址。使用服务器地址代替。 状态: 列出“/”的目录成功

zhxzhlx avatar Oct 31 '19 08:10 zhxzhlx

Thanks a ton @aliquid for fixing this long standing issue. Gone live with 29.0.0.

@JWcodeDev @molekamp @greydmar @fschwengsbier All are suggested to grab the latest version and see if it solves their problem:

https://www.nuget.org/packages/FluentFTP/29.0.0

If you still see errors, decrease the NoopInterval value and try again. Ensure its more than 5000 though as values lower than that would not have any benefit.

robinrodricks avatar Jan 06 '20 09:01 robinrodricks

Hello,

I get the same exception (version 29.0.3). It happens after having uploaded approximatively 2.9Gb of data (series of images of around 750Kb in size). The FTP site is a IIS service. I open the connection this way:

_client = new FtpClient(_serverIPAddress);
_client.Credentials = new NetworkCredential(_serverLogin, _serverPassword);
_client.DataConnectionType = FtpDataConnectionType.EPSV;
_client.Port = 21;
_client.Connect();

Then I iterate the folder structure and call: _client.UploadFile(source, dest, FtpRemoteExists.Append);

Note, for some reason the log written by FluentFTP never changes as the source level filters has no effect. Even with SourceLevels.Error or SourceLevels.Critical the error is not written. Log settings used:

   FtpTrace.LogFunctions = false;
            FtpTrace.AddListener(new TextWriterTraceListener(logfile){
                                                                             Filter = new EventTypeFilter(SourceLevels.Error)
                                                                     });

Tried to set NoopInterval from 5000 to 20000, no luck.

  • Log of the exception:

TargetSite: Boolean UploadFileInternal(System.IO.Stream, System.String, Boolean, FluentFTP.FtpRemoteExists, Boolean, Boolean, System.Action1[FluentFTP.FtpProgress]) -------------------- Inner Exception -------------------- > Message: Timed out trying to read data from the socket stream! > Source: FluentFTP > StackTrace: at FluentFTP.FtpSocketStream.Read(Byte[] buffer, Int32 offset, Int32 count) at FluentFTP.FtpSocketStream.ReadLine(Encoding encoding) at FluentFTP.FtpClient.GetReply() at FluentFTP.FtpClient.Execute(String command) at FluentFTP.FtpClient.GetFileSizeInternal(String path, FtpSizeReply sizeReply) at FluentFTP.FtpClient.GetFileSize(String path) at FluentFTP.FtpClient.OpenAppend(String path, FtpDataType type, Boolean checkIfFileExists) at FluentFTP.FtpClient.ResumeUpload(String remotePath, Stream& upStream, Int64 offset, IOException ex) at FluentFTP.FtpClient.UploadFileInternal(Stream fileData, String remotePath, Boolean createRemoteDir, FtpRemoteExists existsMode, Boolean fileExists, Boolean fileExistsKnown, Action1 progress) > TargetSite: Int32 Read(Byte[], Int32, Int32)<CR>

inside686 avatar Jan 22 '20 11:01 inside686

@inside686 This seems to be now occuring at ResumeUpload / ResumeDownload. Fix will have to be attempted.

robinrodricks avatar Jan 28 '20 05:01 robinrodricks

Hi @robinrodricks , thank you for the answer. I can confirm that it is not absorbed as I'm logging the error in my own try/catch block. I have no clue why it happens, it's maybe some network issue on my side because when it does, I can see my Remote Desktop Connection to the server lose its connection as well. Also, it's not a IIS issue because I switched to Filezilla and the same thing happens. Theoretically, it would not be a blocking problem because I implemented a retry logic in case of failure or exception:

 do
                        {
                            if (retryCount > 3)
                            {
                                throw new SFException((int)ErrorCodes.UnableToUploadFile, typeof(ErrorCodes));
                            }

                            try
                            {
                                uploadSucceful = _client.UploadFile(entry, dst + fName, FtpRemoteExists.Overwrite, false, FtpVerify.None, progress => ProgressUpdated?.Invoke(this, new ProgressArg {FileName = dst + fName, Progress = progress.Progress, TransferSpeed = progress.TransferSpeedToString()}));

                                if (!uploadSucceful)
                                {
                                    Task.Delay(Constants.RetryDelay).WaitNotBlockingUI();
                                    retryCount++;
                                }
                            }
                            catch (Exception e)
                            {
                                Task.Delay(Constants.RetryDelay).WaitNotBlockingUI();
                                retryCount++;
                            }
                        }
                        while (!uploadSucceful);

The problem is that, in that case, I cannot do anything on the file that was being transferred when the timeout exception occurred because it seems to be locked. If I use FtpRemoteExists.Overwrite I get a "Failed to delete the file" exception. If I use FtpRemoteExists.Append I get a "You cannot modify the position of a FtpDataStream. This property is updated as data is read or written to the stream." exception. Now the very strange thing is that even when I dispose and recreate/reconnect the client before retrying, it is the same, the file remains locked and nothing can be done, is that supposed to happen and should I open a new Issue specific to that?

inside686 avatar Jan 28 '20 10:01 inside686

Hi, I am intermittently facing this same issue when trying to connect via FTPS (EPSV) to a server. I've tried two different servers and am having the same problem. I am running the library from within an Azure VM if that is any help. When it fails, it fails before any other commands can be sent after establishing the connection:

04/08/2020 09:02:53 Status: Connecting to xxx.xxx.xx.xxx:990 04/08/2020 09:02:53 Status: FTPS Authentication Successful 04/08/2020 09:02:53 Status: Time to activate encryption: 0h 0m 0s. Total Seconds: 0.3547991. 04/08/2020 09:03:08 Status: Disposing FtpSocketStream...

The server logs on the failed connections are all similar to the below: (069757)4/08/2020 9:02:53 AM - (not logged in) (xx.xxx.xxx.xxx)> Connected, sending welcome message... (069757)4/08/2020 9:02:53 AM - (not logged in) (xx.xxx.xxx.xxx)> 220-FileZilla Server version 0.9.41 beta (069757)4/08/2020 9:02:53 AM - (not logged in) (xx.xxx.xxx.xxx)> 220-written by Tim Kosse ([email protected]) (069757)4/08/2020 9:02:53 AM - (not logged in) (xx.xxx.xxx.xxx)> 220 Please visit http://sourceforge.net/projects/filezilla/ (069757)4/08/2020 9:02:53 AM - (not logged in) (xx.xxx.xxx.xxx)> SSL connection established (069757)4/08/2020 9:03:08 AM - (not logged in) (xx.xxx.xxx.xxx)> disconnected.

It fails 2/3 times when I try via the VM, the other time it successfully uploads a couple of small files (less than 2mb).

I cannot reproduce the error when working within my development environment. This issue has me totally stumped.

fayezm avatar Aug 03 '20 23:08 fayezm

Just a follow up on this - we were using .net core v2 when this issue was occurring, hosted on both Linux and Windows. As an act of desperation, we re-wrote our application targeting .NET Framework 4.7 and this issue does not occur at all.

fayezm avatar Aug 19 '20 00:08 fayezm

I do have this error seems like when doing GetListing() using net core v3

Status: Disposing FtpSocketStream... Warning: FtpClient.Disconnect(): Exception caught and discarded while closing control connection: System.TimeoutException: Timed out trying to read data from the socket stream! at FluentFTP.FtpSocketStream.ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken token) at FluentFTP.FtpSocketStream.ReadLineAsync(Encoding encoding, CancellationToken token) at FluentFTP.FtpClient.GetReplyAsync(CancellationToken token) at FluentFTP.FtpClient.ExecuteAsync(String command, CancellationToken token) at FluentFTP.FtpClient.DisconnectAsync(CancellationToken token) Status: Disposing FtpSocketStream...

Hidend avatar Nov 16 '20 16:11 Hidend

Hi, I have this exception when trying read file from ftp server and file starts with "220" and has few strings. For example, text in file:

220someText
someText2

Code:

static void Main(string[] args)
{
    RunFTP();
}
static void RunFTP()
{
    string hostname = "192.168.1.229";
    int port = 21;
    string username = "FTP_User";
    string password = "123";
    string fileName = @"Test/Test220.txt";

    FtpClient client = new FtpClient(hostname, port, username, password);
    List<FtpProfile> profile = client.AutoDetect();
    client.LoadProfile(profile[0]);
    client.Connect();

    string[] data = GetDataFromFile(fileName, client);

    Console.ReadKey();
}

Tried this way:

private static string[] GetDataFromFile(string _fileName, FtpClient _client)
{
    try
    {
        return ReadLines(() => _client.OpenRead(_fileName), encoding).ToArray();
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        return null;
    }
}
private static IEnumerable<string> ReadLines(Func<Stream> _streamProvider, Encoding _encoding)
{
    using (var stream = _streamProvider())
    using (var reader = new StreamReader(stream, _encoding))
    {
        string line;

        while ((line = reader.ReadLine()) != null)
            yield return line;
    }
}

And this:

private static string[] GetDataFromFile(string _fileName, FtpClient _client)
{
    try
    {
        using (MemoryStream stream = new MemoryStream())
        {
            bool status = _client.Download(stream, _fileName);
            stream.Position = 0;
            List<string> data = new List<string>();
            using (var reader = new StreamReader(stream, encoding))
            {
                string line;

                while ((line = reader.ReadLine()) != null)
                    data.Add(line);
            }
            return data.ToArray();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        return null;
    }
}

Both ways works when file data don't start on "220". If start, first string reads and then when trying to read next string throw exception: "Timed out trying to read data from the socket stream"

.Net framework 4.0 FluentFtp version: 33.0.3

VictorKrs avatar Feb 09 '21 10:02 VictorKrs

Does this issue still need help? Happy to work on it.

parthvnp avatar Feb 23 '23 05:02 parthvnp

Closing. Please open separate new issues if you encounter problems.

FanDjango avatar Feb 24 '23 11:02 FanDjango

PLEASE OPEN NEW ISSUES IF YOU ENCOUNTER THIS ISSUE.

DO NOT ADD YOUR COMMENT HERE.

WE WILL NOT DEBUG OLDER VERSIONS OF FLUENT FTP. SO ENSURE YOU ARE USING THE LATEST VERSION.

robinrodricks avatar Nov 16 '23 09:11 robinrodricks