I have to get the size of a file from ftp. I get this error
Unable to cast object of type 'System.Net.FileWebRequest' to type 'System.Net.FtpWebRequest'
on the line I create the FtpWebRequest object. Here is the code I have at the moment:
public static long FtpGetFileSize(string uri, string username, string password)
{
// Get the object used to communicate with the server
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
request.Method = WebRequestMethods.Ftp.GetFileSize;
// Get network credentials.
request.Credentials = new NetworkCredential(username, password);
try
{
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
// Return the size.
Console.WriteLine("El tamaño del archivo es {0}",response.ContentLength);
return response.ContentLength;
}
}
catch (Exception ex)
{
// If the file doesn't exist, return -1
// Otherwise rethrow the error
if (ex.Message.Contains("File unavailable")) return -1;
throw;
}
}
You can't convert the
WebRequest
toFtpWebRequest
. The problem is thaturi
you must be passing a local path in your parameter, and that is why that exception appears. You need to make sure that the parameter you pass inuri
is a valid ftp address.