FtpWebRequest.Timeout 屬性

定義

取得或設定等待要求的毫秒數。

C#
public override int Timeout { get; set; }

屬性值

Int32值,其中包含要求逾時之前要等候的毫秒數。預設值為 Infinite

例外狀況

指定的值小於零且不是 Infinite

由於已經在進行的要求,已為這個屬性指定新的值。

範例

下列程式代碼範例會設定這個屬性。

C#
public static bool UploadUniqueFileOnServer (Uri serverUri, string fileName)
{
    // The URI described by serverUri should use the ftp:// scheme.
    // It contains the name of the directory on the server.
    // Example: ftp://contoso.com.
    //
    // The fileName parameter identifies the file containing the data to be uploaded.

    if (serverUri.Scheme != Uri.UriSchemeFtp)
    {
        return false;
    }
    // Get the object used to communicate with the server.
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
    request.Method = WebRequestMethods.Ftp.UploadFileWithUniqueName;
    // Set a time limit for the operation to complete.
    request.Timeout = 600000;

    // Copy the file contents to the request stream.
    const int bufferLength = 2048;
    byte[] buffer = new byte[bufferLength];
    int count = 0;
    int readBytes = 0;
    FileStream stream = File.OpenRead(fileName);
    Stream requestStream = request.GetRequestStream();
    do
    {
        readBytes = stream.Read(buffer, 0, bufferLength);
        requestStream.Write(buffer, 0, bufferLength);
        count += readBytes;
    }
    while (readBytes != 0);

    Console.WriteLine ("Writing {0} bytes to the stream.", count);
    // IMPORTANT: Close the request stream before sending the request.
    requestStream.Close();
    FtpWebResponse response = (FtpWebResponse) request.GetResponse();
    Console.WriteLine("Upload status: {0}, {1}",response.StatusCode, response.StatusDescription);
    Console.WriteLine ("File name: {0}", response.ResponseUri);
    response.Close();
    return true;
}

備註

若要指定無限值,請將 Timeout 屬性設定為 Infinite (-1) 。 這是預設值。

Timeout 是使用 GetResponse 方法進行的同步要求等候回應以及 GetRequestStream 方法等候數據流的毫秒數。 如果資源未在逾時期間內回應,要求會 WebException 擲回 ,並將 Status 屬性設定為 Timeout

在呼叫、 或 方法之後變更Timeout會導致例外狀況。BeginGetRequestStreamBeginGetResponseGetResponseGetRequestStreamInvalidOperationException

功能變數名稱系統 (DNS) 查詢最多可能需要 15 秒才能傳回或逾時。如果您的要求包含需要解析的主機名,而且您設定 Timeout 為小於 15 秒的值,則擲回 之前 WebException 可能需要 15 秒以上的時間,以指出要求逾時。

適用於

產品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

另請參閱