Quantcast
Channel: System.Net.FtpClient
Viewing all 741 articles
Browse latest View live

New Post: SocketException in windows service

$
0
0
Hi,

I am trying to use FtpClient in windows service on Windows XP machine. No matter what I try, I am not even able to make the connection. Here is my code
            using(FtpClient con = new FtpClient()) {
                
                con.EnableThreadSafeDataConnections = false;
                
                con.Host = "XYZ";
                
                
                con.Credentials = new System.Net.NetworkCredential("anonymous","abc@xyz.com");
                
                using(var istream = con.OpenRead("/ROOT/Testing_Drop/Dump/chile.txt.txt", FtpDataType
                                                 .ASCII))
                {
                    string jobfilename = @"C:\Documents and Settings\manesing\My Documents\Work Area\Chile.txt";
                    using(var output=new BinaryWriter(File.Open(jobfilename, FileMode.Create))) {
                        
                        
                        byte[] buf = new byte[8192];
                        int read = 0;
                        try {
                            while ((read = istream.Read(buf, 0, buf.Length)) > 0) {
                                output.Write(buf,0,read);
                            }
                        }
                        catch(Exception ex)
                        {
                            EventLog.WriteEntry("TestFTP","FTP: " +ex.Message);
                        }
                        finally {
                            
                            istream.Close();
                        }


                        
                    }
                }
            }
The windows service always crash with below exception.
Service cannot be started. System.Net.Sockets.SocketException (0x80004005): An invalid argument was supplied
   at System.Net.Sockets.DynamicWinsockMethods.LoadDynamicFunctionPointer(SafeCloseSocket socketHandle, Guid& guid)
   at System.Net.Sockets.DynamicWinsockMethods.EnsureConnectEx(SafeCloseSocket socketHandle)
   at System.Net.Sockets.DynamicWinsockMethods.GetDelegate[T](SafeCloseSocket socketHandle)
   at System.Net.Sockets.Socket.ConnectEx(SafeCloseSocket socketHandle, IntPtr socketAddress, Int32 socketAddressSize, IntPtr buffer, Int32 dataLength, Int32& bytesSent, SafeHandle overlapped)
   at System.Net.Sockets.Socket.BeginConnectEx(EndPoint remoteEP, Boolean flowContext, AsyncCallback callback, Object state)
   at System.Net.Sockets.Socket.BeginConnect(EndPoint remoteEP, AsyncCallback callback, Object state)
   at System.Net.Sockets.Socket.BeginConnect(IPAddress address, Int32 port, AsyncCallback requestCallback, Object state)
   at System.Net.FtpClient.FtpSocketStream.Connect(String host, Int32 port, FtpIpVersion ...
As I could run the same code in the console application, I was suspecting the issue with user permission. However, when I tried .NET native FTPWebRequest class, it worked without any issues.
I can even connect to FTP server using sockets and it connects just fine. Windows service is running with admin user privileges.


Here is the FTPTrace output:
Disposing FtpClient object...
Disposing FtpClient object...
Disposing FtpSocketStream...
As you can see, even the connection is not made. Let me know if I am missing something in the code.
FtpClient version is 1.0.5281.14359

New Post: SocketException in windows service

$
0
0
Hi,

For anyone facing the same issue, I finally found that the Winsock2 was corrupted on my system.

http://support.microsoft.com/kb/811259

Followed the above link and was able to correct the problem. Now FtpClient works as it should.

Here is the workstation information
OS Name: Microsoft Windows XP Professional
OS Version: 5.1.2600 Service Pack 3 Build 2600

Created Unassigned: Null reference exception in GetObjectInfo [385]

$
0
0

Null exception is throwed by the "getObjectInfo" method calling the FtpListItem.Parse method with null as path,

To fix it, is needed a null checking in the "remove globbing/wildcar from path" code;

// remove globbing/wildcard from path
if (path != null && path.GetFtpFileName().Contains("*")) {
path = path.GetFtpDirectoryName();
}

Seems that other parts of the FtpListItem.Parse method need to check null values too.

Edited Unassigned: Null reference exception in GetObjectInfo [385]

$
0
0

Null exception is throwed by the "getObjectInfo" method calling the FtpListItem.Parse method with null as path,

To fix it, is needed a null checking in the "remove globbing/wildcar from path" code;

// remove globbing/wildcard from path
if (path != null && path.GetFtpFileName().Contains("*")) {
path = path.GetFtpDirectoryName();
}

Seems that other parts of the FtpListItem.Parse method need to check null values too.

Edited Unassigned: Null reference exception in GetObjectInfo [385]

$
0
0

Null exception is throwed by the FtpClient.GetObjectInfo method calling the FtpListItem.Parse method being path = null:

return FtpListItem.Parse(null, info, Capabilities);

To fix it, is needed a null checking in the "remove globbing/wildcar from path" code;

// remove globbing/wildcard from path
if (path != null && path.GetFtpFileName().Contains("*")) {
path = path.GetFtpDirectoryName();
}

Seems that other parts of the FtpListItem.Parse method need to check null values too.

New Post: FTP File Upload Issue - Please help

$
0
0
Hi,

We had a file upload code working to a particular FTP location. I was trying to implement FTPClient instead of my old working code. I downloaded the latest version and wrote a sample code. Please find below the Code I used for FTP File Upload.
public static void OpenWrite()
        {

            var ftpClient = new FtpClient
            {
                Host = "sftp.****.com",
                Port = 21,
                DataConnectionEncryption = true,
                EncryptionMode = FtpEncryptionMode.Explicit,
                SocketKeepAlive = false,
                DataConnectionType = FtpDataConnectionType.AutoPassive,
                Credentials = new NetworkCredential("*****", "*****"),
                DataConnectionConnectTimeout = 3000000,
                DataConnectionReadTimeout = 3000000,
                ConnectTimeout = 3000000,
                ReadTimeout = 3000000,
                SocketPollInterval = 0
            };

           
            using (ftpClient)
            {
                var destPath = "/test.txt";
                var sourcePath = ApplicationBaseFolder + @"\test.txt";

                ftpClient.ValidateCertificate += (control, e) => { e.Accept = true; };

                const int BUFFER_SIZE = 64 * 1024; // 64KB buffer
                byte[] buffer = new byte[BUFFER_SIZE];
                using (Stream readStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
                using (Stream writeStream = ftpClient.OpenWrite(destPath))
                {
                    while (readStream.Position < readStream.Length)
                    {
                        buffer.Initialize();
                        int bytesRead = readStream.Read(buffer, 0, BUFFER_SIZE);
                        writeStream.Write(buffer, 0, bytesRead);
                    }
                    writeStream.Flush();
                }
            }            
        }
On testing to a test FTP location, it worked great. But, When i Tried to our production FTP location, it failed with the following Error Log.
InterNetwork: 12.68.144.205
220-Security Notice
220-You are about to access a secured resource. AmerisourceBergen Specialty
220-Group reserves the right to monitor and/or limit access to this
220 resource at any time.
AUTH TLS
234 SSL enabled start the negotiation
Time to activate encryption: 0h 0m 0s, Total Seconds: 0.5468995.
USER sigmatau
331 Password required for sigmatau
PASS <omitted>
230-Welcome to AmerisourceBergen Specialty Group! Please watch this area
230-for important messages.
230 User sigmatau logged in.
PBSZ 0
200 PBSZ command successful
PROT P
200 PROT command successful
FEAT
211-Extensions supported:
  AUTH SSL
  AUTH TLS-P
  AUTH TLS
  AUTH TLS-C
  PROT
  PBSZ
  SIZE
  CCC
  REST STREAM
  MODE Z
  XSHA1
  INTEGRITY
  HASH
  CLNT
211 End of list
Text encoding: System.Text.ASCIIEncoding
InterNetwork: 12.68.144.205
220-Security Notice
220-You are about to access a secured resource. AmerisourceBergen Specialty
220-Group reserves the right to monitor and/or limit access to this
220 resource at any time.
AUTH TLS
234 SSL enabled start the negotiation
Time to activate encryption: 0h 0m 0s, Total Seconds: 0.1093799.
USER sigmatau
331 Password required for sigmatau
PASS <omitted>
230-Welcome to AmerisourceBergen Specialty Group! Please watch this area
230-for important messages.
230 User sigmatau logged in.
PBSZ 0
200 PBSZ command successful
PROT P
200 PROT command successful
Text encoding: System.Text.ASCIIEncoding
PWD
257 "/Home/sigmatau" is current directory
CWD /Home/sigmatau
250 CWD command successful
TYPE I
200 TYPE command successful
SIZE /test.txt
550 SIZE failed: File could not be found
EPSV
502 Command not implemented
PASV
227 Entering Passive Mode (10,212,18,22,11,225)
InterNetwork: 10.212.18.22
Disposing FtpClient object...
QUIT
221 Goodbye
Disposing FtpSocketStream...
System.Net.Sockets.SocketException (0x80004005): A connection attempt failed bec
ause the connected party did not properly respond after a period of time, or est
ablished connection failed because connected host has failed to respond 10.212.1
8.22:3041
   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
   at System.Net.FtpClient.FtpSocketStream.Connect(String host, Int32 port, FtpI
pVersion ipVersions) in c:\Sreehari\RnD\System.Net.FtpClient\source\FtpSocketStr
eam.cs:line 607
   at System.Net.FtpClient.FtpClient.OpenPassiveDataStream(FtpDataConnectionType
 type, String command, Int64 restart) in c:\Sreehari\RnD\System.Net.FtpClient\so
urce\FtpClient.cs:line 1130
   at System.Net.FtpClient.FtpClient.OpenPassiveDataStream(FtpDataConnectionType
 type, String command, Int64 restart) in c:\Sreehari\RnD\System.Net.FtpClient\so
urce\FtpClient.cs:line 1083
   at System.Net.FtpClient.FtpClient.OpenDataStream(String command, Int64 restar
t) in c:\Sreehari\RnD\System.Net.FtpClient\source\FtpClient.cs:line 1284
   at System.Net.FtpClient.FtpClient.OpenWrite(String path, FtpDataType type) in
 c:\Sreehari\RnD\System.Net.FtpClient\source\FtpClient.cs:line 1528
   at System.Net.FtpClient.FtpClient.OpenWrite(String path) in c:\Sreehari\RnD\S
ystem.Net.FtpClient\source\FtpClient.cs:line 1499
   at Examples.OpenWriteExample.OpenWrite() in c:\Sreehari\RnD\System.Net.FtpCli
ent\examples\OpenWrite.cs:line 77
   at Examples.MainClass.Main(String[] args) in c:\Sreehari\RnD\System.Net.FtpCl
ient\examples\Main.cs:line 28
Please help me to troubleshoot the issue.

Thanks,
Sreehari

Created Unassigned: Unhandled Exception [386]

$
0
0
testing robustness and turned off my network io. tried to connect. receive an unhandled exception, host unreachable at m_socket.EndConnect(ar); in FtpSocketStream. I am catching exceptions at the top level method call.

New Post: Download file invalid size

$
0
0
Hi,
Sorry relay late. I try to download XML file and try to open with IE, Chrome, XML Editor, it raise message :
I used standard download function of FTP Client libs:

objFTpClient.Download(strPath & "/" & obj.Name, "\filename.xml")

"error on line 2 at column 230: Extra content at the end of the document"

Original XML file :

<ns0:MT_Promotion xmlns:ns0="http://company.com/PDW/ArticleMaster">
<IDoc>
<Header>
<IDOCType>OUTBOUND_PROMOTION</IDOCType>
<OutDate>13/08/2014 23:06:31</OutDate>
<SITECode>SG01</SITECode>
<IDocNo>0000000000436327201408131112025-B</IDocNo>
<Count>0</Count>
</Header>
</IDoc>
</ns0:MT_Promotion>

After download :

<?xml version="1.0" encoding="UTF-8"?>
<ns0:MT_Promotion xmlns:ns0="http://NK.com/PDW/ArticleMaster">
OUTBOUND_PROMOTION20/08/2014
23:04:02</OutDate><SITECode>SG01</SITECode><IDocNo>0000000000692126201408201109043-B</IDocNo><Count>0</Count></Header></IDoc></ns0:MT_Promotion>>

New Post: Async OpenWrite and Cannot Find Path Specified

$
0
0
Hi. Great library! Thanks for putting it together. I am using it in a Windows service to upload files from one server to another (Microsoft FTP Service). I am using BeginOpenWrite and it works perfectly if the folder for the file exists on the destination server. The problem is that this will not always be the case. Do you have any suggestions as to how to check that the folder structure exists and create it, if necessary, in the context of an async call? Is there a way to do that using the current library or should I add an overload to BeginOpenWrite with a "force" parameter to check the folder structure first?

Thanks,

David Perry

New Post: SSL\TLS GetListing() can't list subdirectories items

$
0
0
example:
Ftp Server:
/downloads            Dir
/downloads/a.xml   File
TLS  Mode

                conn.Host = "127.0.0.1";
                conn.Port = 990;
                conn.EncryptionMode = FtpEncryptionMode.Implicit;
                conn.SocketKeepAlive = false;
                conn.DataConnectionType = FtpDataConnectionType.PASV;
                conn.DataConnectionEncryption = true;
                conn.Credentials = new NetworkCredential("test", "test");
                conn.ValidateCertificate += (control, ev) => { ev.Accept = true; };
                conn.Encoding = System.Text.Encoding.Default;

                var path = "/downloads";
                var items = conn.GetListing(path);

Result is error, items[0].FullName : "/downloads/downloads"
BUT:
                conn.Host = "127.0.0.1";
                conn.Port = 21;
                conn.Credentials = new NetworkCredential("test", "test");

                var path = "/downloads";
                var items = conn.GetListing(path);

Result is right, items[0].FullName: "/downloads/a.xml"

New Post: Is the underlying TLS encryption affected by Heartbleed bug?

$
0
0
I'm not sure what is used for the underlying TLS/SSL encryption, so I just wanted to check. I did not see any fixes in the recent change history.

New Post: Provide a way to override the host/port of a passive data connection

$
0
0
Hello,

First of all, thank you for writing this library.

I have a feature request: please add an event or callback into OpenPassiveDataStream that let the user of the library change the host/port that will be used to open the data connection. The callback should be provided with the host and port returned by EPSV or PASV.

Now the reason behind the request: I'm connecting to a FTP server through a SSH tunnel. When opening the data connection, I need to create a new tunnel to the data end point. I have no problem doing this (I'm using the SSH.NET library to do so), but I obviously need the host and port returned by the FTP server, as well as tell the FTP client where it should connect to (my tunnel instead of the original end point).

Thanks!

New Post: Is the underlying TLS encryption affected by Heartbleed bug?

$
0
0
No, heartbleed affects OpenSSL only.
FtpClient uses SslStream which uses a Microsoft implementation and not the OpenSSL one, so it's not affected.

New Post: GetListing(), Modified value not used on Server with "MDTM" Support

$
0
0
Hello,
i've encountered a problem using the GetListing() method. If the Server has "MDTM" support it is not possible to use the modified values of the servers file-listing.
I can force to receive the modified values calling .GetListing("/",FtpListOption.Modify), but this is very slow on large listings and it is depending on the latency of the network.
A FtpListOption to force the usage of the modified values of the servers file-listing would be very nice. Perhaps it is even better to use the inaccurate modified values of the servers file-listing and then to override this values if "FtpListOption.Modify" is used.

New Post: Speed up FileExists when using option NLST?

$
0
0
Hi,

the current implentation of FileExists uses GetListing which returns all files and dirs in a folder.
But if the NLST is used, for each item, there is an check whether the file is a directory or not.
This is causing a lot of traffic because we only want to now this for one item.

A switch should be added to check on for this on demand (If NLST is used)):
FileExists -> Get all items -> Check if item exists in list [no check] -> Check if item is file (expensive if NLST)
Currently it is:
FileExists -> Get all items -> For all items: Check: Is File or Directory (expensive if NLST) -> Check if item exists.

Thanks.

New Post: Speed up FileExists when using option NLST?

$
0
0
If you want something faster the first thing you need to do is switch to a server that supports MLSD/MLST and use GetObjectInfo(). That's the best you're going to get; if I take the check out of GetListing() then FileExists() no longer does what the name of the method implies.

New Post: Speed up FileExists when using option NLST?

$
0
0
Look at the code for GetObjectInfo(), the same approach can be used in this case:
if(serverSupportsMLSD) {
    // use FtpClient.GetObjectInfo() because it's the fastest
}
else {
    // use slower GetListing() based methods because server only supports NLST or LIST.
}

New Post: Speed up FileExists when using option NLST?

$
0
0
jptrosclair wrote:
if I take the check out of GetListing() then FileExists() no longer does what the name of the method implies.
Why? The current implementation of FileExists with GetListing() is good (same approch for several kinds of listings) but certainly an overkill: Iterating over all files/dirs just for one item is very expensive. If the file check is just performed for the desired item, the behaviour is similar.
I will write an new implementation and post a patch if you dont mind. I do not have much experience in FTP and maybe I made a mistake in my quick analysis.

New Post: Speed up FileExists when using option NLST?

$
0
0
I did some performance tests and I must admit that the speed gain is minimal: Connect and Auth take most of the time.

But the performance is now stable: It does not matter how many files there are, DirectoryExists is only called 1 plus 1 and not 1 plus n times [NLST only!].

Maybe you can use it...
diff --git "a/FtpClient-d611c8a-left.cs" "b/FtpClient.cs"
index 0b3718d..24881e7 100644
--- "a/FtpClient-d611c8a-left.cs"
+++ "b/FtpClient.cs"
 
 namespace System.Net.FtpClient {
     /// <summary>
@@ -2083,6 +2085,80 @@ namespace System.Net.FtpClient {
         }
 
         /// <summary>
+        /// Checks if a file exsts on the server by using the NLST
+        /// command.
+        /// </summary>
+        /// <param name="path">The full or relative path to the file</param>
+        /// <returns>True if the file exists</returns>
+        private bool NameListFileExists(string path)
+        {
+            string ftpFileName = path.GetFtpFileName();
+            string pwd = GetWorkingDirectory();
+            string hit = null;
+
+            path = path.GetFtpPath();
+            if (path == null || path.Trim().Length == 0)
+            {
+                if (pwd != null && pwd.Trim().Length > 0)
+                    path = pwd;
+                else
+                    path = "./";
+            }
+            else if (!path.StartsWith("/") && pwd != null && pwd.Trim().Length > 0)
+            {
+                if (path.StartsWith("./"))
+                    path = path.Remove(0, 2);
+                path = string.Format("{0}/{1}", pwd, path).GetFtpPath();
+            }
+
+            try
+            {
+                m_lock.WaitOne();
+
+                Execute("TYPE I");
+
+                
+
+                // read in raw file listing
+                using (FtpDataStream stream = OpenDataStream(string.Format("NLST {0}", path.GetFtpPath()), 0))
+                {
+                    try
+                    {
+                        string buf;
+                        while ((buf = stream.ReadLine(Encoding)) != null)
+                        {
+                            if (hit == null && buf.Length > 0)
+                            {
+                                if (buf.GetFtpFileName() == ftpFileName)
+                                {
+                                    hit = buf;
+                                }
+                            }
+                        }
+                    }
+                    finally
+                    {
+                        stream.Close();
+                    }
+                }
+            }
+            finally
+            {
+                m_lock.ReleaseMutex();
+            }
+
+            if (hit != null)
+            {
+                if (DirectoryExists(hit))
+                    return false;
+                else
+                    return true;
+            }
+
+            return false;
+        }
+
+        /// <summary>
         /// Gets a file listing from the server asynchronously
         /// </summary>
         /// <param name="callback">AsyncCallback method</param>
@@ -2815,9 +2891,23 @@ namespace System.Net.FtpClient {
                 if (!DirectoryExists(dirname))
                     return false;
 
-                foreach (FtpListItem item in GetListing(dirname, options))
-                    if (item.Type == FtpFileSystemObjectType.File && item.Name == path.GetFtpFileName())
-                        return true;
+                // Reduce the overhead of GetListing in case the NLST command
+                // is used (MLSD is a good fast alternative, too)
+                if ((options & FtpListOption.NameList) == FtpListOption.NameList)
+                {
+                    return NameListFileExists(path);
+                }
+                else
+                {
+                    // Check if the file exists using the listing
+                    string ftpFileName = path.GetFtpFileName();
+                    foreach (FtpListItem item in GetListing(dirname, options))
+                    {
+                        if (item.Type == FtpFileSystemObjectType.File && item.Name == ftpFileName)
+                            return true;
+                    }
+                }
+                
             }
             finally {
                 m_lock.ReleaseMutex();

New Post: Maximum file size was exceeded

$
0
0
I am facing a problem when user uploads a file with size more than 50 MB. Ftp code is throwing exception "Maximum file size was exceeded". I have placed code below, can anybody help me I need it on urgent basis.
if (ftp.IsConnected)
                                {
                                    var destPath = Convert.ToString(Session["fullpath"]);
                                    int BUFFER_SIZE = file.ContentLength; // 64KB buffer
                                    byte[] buffer = new byte[file.ContentLength];
                                    using (Stream readStream = file.InputStream)
                                    using (Stream writeStream = ftp.OpenWrite(string.Format("{0}/{1}", destPath, file.FileName)))
                                    {
                                        while (readStream.Position < readStream.Length)
                                        {
                                            buffer.Initialize();
                                           int bytesRead = readStream.Read(buffer, 0, BUFFER_SIZE);
                                           writeStream.Write(buffer, 0, bytesRead);
                                       }
                                        ViewState["fileContentLenght"] = file.ContentLength;
                                        writeStream.Flush();

                                    }
                                }
Viewing all 741 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>