FtpWebRequest.GetRequestStream Метод

Определение

Возвращает поток, используемый для выгрузки данных на FTP-сервер.

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

Возвращаемое значение

Доступный для записи экземпляр Stream, используемый для хранения данных, отправляемых на сервер текущим запросом.

Исключения

Метод BeginGetRequestStream(AsyncCallback, Object) был вызван, но не был завершен.

-или-

Прокси-сервер HTTP включен, и была предпринята попытка использования FTP-команды, отличной от DownloadFile, ListDirectory или ListDirectoryDetails.

Не удается установить подключение к FTP-серверу.

Свойству Method не присвоено значение UploadFile или AppendFile.

Примеры

В следующем примере кода показано копирование файла в поток данных запроса и отправка запроса на сервер для отправки данных и их добавления в файл.

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;
}

Комментарии

Задайте свойства запроса перед вызовом GetRequestStream метода . После записи данных в поток необходимо закрыть поток перед отправкой запроса.

Если вы не задали Method для свойства значение UploadFile или AppendFile, вы не сможете получить поток.

GetRequestStream блоки во время ожидания потока. Чтобы избежать этого, вызовите BeginGetRequestStream метод вместо GetRequestStream.

Примечание

Данный член генерирует сведения трассировки, если в приложении включена трассировка сети. Дополнительные сведения см. в разделе Трассировка сети в платформа .NET Framework.

Примечания для тех, кто вызывает этот метод

Этот метод создает сетевой трафик.

Применяется к

См. также раздел