FtpWebRequest.GetRequestStream Método

Definição

Recupera o fluxo usado para carregar dados para um servidor FTP.Retrieves the stream used to upload data to an FTP server.

public:
 override System::IO::Stream ^ GetRequestStream();
public override System.IO.Stream GetRequestStream ();
override this.GetRequestStream : unit -> System.IO.Stream
Public Overrides Function GetRequestStream () As Stream

Retornos

Stream

Uma instância Stream gravável usada para armazenar dados a serem enviados para o servidor pela solicitação atual.A writable Stream instance used to store data to be sent to the server by the current request.

Exceções

BeginGetRequestStream(AsyncCallback, Object) foi chamado e não foi concluído.BeginGetRequestStream(AsyncCallback, Object) has been called and has not completed.

- ou --or- Um proxy HTTP está habilitado e você tentou usar um comando FTP diferente de DownloadFile, ListDirectory ou ListDirectoryDetails.An HTTP proxy is enabled, and you attempted to use an FTP command other than DownloadFile, ListDirectory, or ListDirectoryDetails.

Não foi possível estabelecer uma conexão com o servidor FTP.A connection to the FTP server could not be established.

A propriedade Method não foi definida como UploadFile ou AppendFile.The Method property is not set to UploadFile or AppendFile.

Exemplos

O exemplo de código a seguir demonstra a cópia de um arquivo para o fluxo de dados de uma solicitação e o envio de uma solicitação ao servidor para carregar os dados e acrescentá-los a um arquivo.The following code example demonstrates copying a file to a request's data stream and sending a request to the server to upload the data and append it to a file.

static bool AppendFileOnServer( String^ fileName, Uri^ serverUri )
{
   // The URI described by serverUri should use the ftp:// scheme.
   // It contains the name of the file on the server.
   // Example: ftp://contoso.com/someFile.txt. 
   // The fileName parameter identifies the file containing 
   // the data to be appended to the file on the server.
   if ( serverUri->Scheme != Uri::UriSchemeFtp )
   {
      return false;
   }

   // Get the object used to communicate with the server.
   FtpWebRequest^ request = dynamic_cast<FtpWebRequest^>(WebRequest::Create( serverUri ));
   request->Method = WebRequestMethods::Ftp::AppendFile;
   StreamReader^ sourceStream = gcnew StreamReader( fileName );
   array<Byte>^fileContents = Encoding::UTF8->GetBytes( sourceStream->ReadToEnd() );
   sourceStream->Close();
   request->ContentLength = fileContents->Length;

   // This example assumes the FTP site uses anonymous logon.
   request->Credentials = gcnew NetworkCredential( "anonymous","janeDoe@contoso.com" );
   Stream^ requestStream = request->GetRequestStream();
   requestStream->Write( fileContents, 0, fileContents->Length );
   requestStream->Close();
   FtpWebResponse^ response = dynamic_cast<FtpWebResponse^>(request->GetResponse());
   Console::WriteLine( "Append status: {0}", response->StatusDescription );
   response->Close();
   return true;
}
public static bool AppendFileOnServer(string fileName, Uri serverUri)
{
    // The URI described by serverUri should use the ftp:// scheme.
    // It contains the name of the file on the server.
    // Example: ftp://contoso.com/someFile.txt.
    // The fileName parameter identifies the file containing
    // the data to be appended to the file on the server.

    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.AppendFile;

    StreamReader sourceStream = new StreamReader(fileName);
    byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
    sourceStream.Close();
    request.ContentLength = fileContents.Length;

    // This example assumes the FTP site uses anonymous logon.
    request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(fileContents, 0, fileContents.Length);
    requestStream.Close();
    FtpWebResponse response = (FtpWebResponse) request.GetResponse();

    Console.WriteLine("Append status: {0}",response.StatusDescription);

    response.Close();
    return true;
}

Comentários

Defina as propriedades da solicitação antes de chamar o GetRequestStream método.Set the request properties before calling the GetRequestStream method. Depois de gravar os dados no fluxo, você deve fechar o fluxo antes de enviar a solicitação.After writing the data to the stream, you must close the stream prior to sending the request.

Se você não tiver definido a Method propriedade como UploadFile ou AppendFile , não será possível obter o fluxo.If you have not set the Method property to UploadFile or AppendFile, you cannot get the stream.

GetRequestStream blocos enquanto aguarda o fluxo.GetRequestStream blocks while waiting for the stream. Para evitar isso, chame o BeginGetRequestStream método no lugar de GetRequestStream .To prevent this, call the BeginGetRequestStream method in place of GetRequestStream.

Observação

Esse membro emite o rastreamento de informações quando você ativa o rastreamento de rede em seu aplicativo.This member outputs trace information when you enable network tracing in your application. Para obter mais informações, consulte rastreamento de rede na .NET Framework.For more information, see Network Tracing in the .NET Framework.

Notas aos Chamadores

Esse método gera o tráfego de rede.This method generates network traffic.

Aplica-se a

Confira também