FtpWebResponse.ContentLength 属性

定义

获取从 FTP 服务器上接收的数据的长度。

public:
 virtual property long ContentLength { long get(); };
public override long ContentLength { get; }
member this.ContentLength : int64
Public Overrides ReadOnly Property ContentLength As Long

属性值

Int64 值,它包含从 FTP 服务器上接收的数据的字节数。

示例

下面的代码示例从 指定的 FTP 服务器上下载文件。 此属性包含下载的文件中的字节数。

public static bool DownloadFileFromServer(Uri serverUri, string localFileName)
{
    // The serverUri parameter should start with the ftp:// scheme.
    if (serverUri.Scheme != Uri.UriSchemeFtp)
    {
        return false;
    }
    // Get the object used to communicate with the server.
    // Note that the cast to FtpWebRequest is done only
    // for the purposes of illustration. If your application
    // does not set any properties other than those defined in the
    // System.Net.WebRequest class, you can use the following line instead:
    // WebRequest request = WebRequest.Create(serverUri);
    //
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
    request.Method = WebRequestMethods.Ftp.DownloadFile;

    FtpWebResponse response = (FtpWebResponse) request.GetResponse();

    Stream responseStream = null;
    StreamReader readStream = null;
    StreamWriter writeStream = null;
    try
    {
        responseStream = response.GetResponseStream();
        readStream = new StreamReader(responseStream, System.Text.Encoding.UTF8);
        // Display information about the data received from the server.
        Console.WriteLine("Bytes received: {0}",response.ContentLength);

        Console.WriteLine("Message from server: {0}", response.StatusDescription);
        Console.WriteLine("Resource: {0}", response.ResponseUri);

        // Write the bytes received from the server to the local file.
        if (readStream != null)
        {
            writeStream = new StreamWriter(localFileName, false);
            writeStream.Write(readStream.ReadToEnd());
        }
    }
    finally
    {
        if (readStream != null)
        {
            readStream.Close();
        }
        if (response != null)
        {
            response.Close();
        }
        if (writeStream != null)
        {
            writeStream.Close();
        }
    }
    return true;
}

注解

当 FTP 服务器返回响应流时, ContentLength 属性包含流中的字节数。 ContentLength 如果响应中未返回任何数据,或者服务器未发送内容长度信息,则返回 。1。 如果已返回或应该返回数据,则返回值大于或等于零。 例如,对于使用 ListDirectory 字段的请求, ContentLength 属性始终返回 。1。 对于使用 UploadFile 方法的请求, ContentLength 属性始终为零。 对于使用 DownloadFile 方法的请求,如果下载的文件包含数据,则 属性大于零;如果为空,则属性为零。

对于使用 GetFileSize 方法的请求, ContentLength 返回服务器上指定文件的大小。

适用于

另请参阅