C# FTP, how to check if a Path is a File or a Dire

2019-06-24 02:15发布

I have an array that contains some FTP pathes, like follows:

"ftp//ip/directory/directory1",
"ftp//ip/directory/directory2",
"ftp//ip/directory/file.txt",
"ftp//ip/directory/directory3",
"ftp//ip/directory/another_file.csv"

How can i find out if the path is a file or a directory?

Thanks in advance.

标签: c# file ftp
7条回答
迷人小祖宗
2楼-- · 2019-06-24 03:18

I had the same problem so I used GetFileSize to check if it's a File or Directory

var isFile = FtpHelper.IsFile("ftpURL", "userName", "password");

using System;
using System.Net;

public static class FtpHelper
{
    public static bool IsFile(Uri requestUri, NetworkCredential networkCredential)
    {
        return GetFtpFileSize(requestUri, networkCredential) != default(long); //It's a Directory if it has no size
    }
    public static FtpWebRequest GetFtpWebRequest(Uri requestUri, NetworkCredential networkCredential, string method = null)
    {
        var ftpWebRequest = (FtpWebRequest)WebRequest.Create(requestUri); //Create FtpWebRequest with given Request Uri.
        ftpWebRequest.Credentials = networkCredential; //Set the Credentials of current FtpWebRequest.

        if (!string.IsNullOrEmpty(method))
            ftpWebRequest.Method = method; //Set the Method of FtpWebRequest incase it has a value.
        return ftpWebRequest; //Return the configured FtpWebRequest.
    }
    public static long GetFtpFileSize(Uri requestUri, NetworkCredential networkCredential)
    {
        //Create ftpWebRequest object with given options to get the File Size. 
        var ftpWebRequest = GetFtpWebRequest(requestUri, networkCredential, WebRequestMethods.Ftp.GetFileSize);

        try { return ((FtpWebResponse)ftpWebRequest.GetResponse()).ContentLength; } //Incase of success it'll return the File Size.
        catch (Exception) { return default(long); } //Incase of fail it'll return default value to check it later.
    }
}
查看更多
登录 后发表回答