开发者

Checking if multiple files exists on FTP server (C#)

I need a way to check if multiple files exist in a given FTP path. I will have a list, which lists all the file names to check, and I will need to check if all these exist on the server, a开发者_StackOverflownd return errors for ones that don't. How easy is this?

Thanks


The safest approach would be to retrieve a list of files/directories per directory and parse that list.

       // Get the object used to communicate with the server.
        var request = WebRequest.Create(url);

        request.Credentials = new NetworkCredential(username, password);

        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

        try
        {
            using(var response = request.GetResponse())
            {
                using(var stream = response.GetResponseStream())
                {
                    using(var reader = new StreamReader(stream))
                    {
                        while(reader.Peek() >= 0)
                        {
                             var line = reader.ReadLine();

                             // check if this is a file or directory, filter list etc..

                        }
                    }
                }
            }
        }
        catch
        {

        }

Another- easier - option would be to try to retrieve the files DateTimestamp and catch the exception if the file doesn't exist. You should check the exception since one could be thrown for a different reason.

        var request = WebRequest.Create(url);

        request.Credentials = new NetworkCredential(username, password);

        request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

        try
        {
            using(var response = (FtpWebResponse)request.GetResponse())
            {
                // file exists
            }
        }
        catch(WebException e)
        {
            // file probably doesn't exits
        }


Well, if you have access to the server, you could write your script there and then just request that script and thus only have to make one server request. Otherwise, you'll just need to check each file, one by one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜