简体   繁体   中英

Identify whether ftp URL is directory name or file using c#

For a ftp path say ftp://ftp.something.com/ I am able to list all directories with this code :

WebRequest req = WebRequest.Create(url) as WebRequest;
        req.Method = WebRequestMethods.Ftp.ListDirectory;

//code to get response from ftp site and list all files and directories path in a list name name_list.

Now foreach path from a list name_list, if path is a directory then I add that path in a list name sub_list else if it is path of some file(.txt, .pdf, .rar, .html, .tw and many more extensions) then add that path in another list name final_list. So far what I am able to do is :

foreach(string url in name_list)
{
 if (Regex.IsMatch(url, ".*?" + @"(\.[A-Za-z]{2,4}$)"))
         //add to sub_list
else
        //add to final_list
}

But this is not a reliable and robust way to achieve my goal. Is there any other best way to this.

I would use the System.IO.Path class to determine if it is a path or file. Specifically: http://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx

You can look at file permissions to see if it is a directory or not. Refer to the following example:

http://www.copyandwaste.com/posts/view/parsing-webrequestmethodsftplistdirectorydetails-and-listdirectory/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM