FileWebRequest FileWebRequest FileWebRequest FileWebRequest Class

Definición

Proporciona una implementación del sistema de archivos de la clase WebRequest.Provides a file system implementation of the WebRequest class.

public ref class FileWebRequest : System::Net::WebRequest, System::Runtime::Serialization::ISerializable
[System.Serializable]
public class FileWebRequest : System.Net.WebRequest, System.Runtime.Serialization.ISerializable
type FileWebRequest = class
    inherit WebRequest
    interface ISerializable
Public Class FileWebRequest
Inherits WebRequest
Implements ISerializable
Herencia
Atributos
Implementaciones

Ejemplos

El siguiente ejemplo de código utiliza el FileWebRequest clase para tener acceso a un recurso de sistema de archivos.The following code example uses the FileWebRequest class to access a file system resource.

// This program creates or open a text file in which it stores a string.
// Both file and string are passed by the user.
// Note. In order for this program to work, the folder containing the test file
// must be shared with its permissions set to allow write access.
#using <System.dll>

using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Net;
ref class TestGetRequestStream
{
private:
   static FileWebRequest^ myFileWebRequest;
   static void showUsage()
   {
      Console::WriteLine( "\nPlease enter file name and timeout :" );
      Console::WriteLine( "Usage: cs_getrequeststream <systemname>/<sharedfoldername>/<filename> timeout" );
      Console::WriteLine( "Example: cs_getrequeststream ndpue/temp/hello.txt 1000" );
      Console::WriteLine( "Small timeout values (for instance 3 or less) cause a timeout exception." );
   }

   static void makeFileRequest( String^ fileName, int timeout )
   {
      try
      {
         
         // Create a Uri object.
         Uri^ myUrl = gcnew Uri( String::Format( "file://{0}", fileName ) );
         
         // Create a FileWebRequest object.
         myFileWebRequest = dynamic_cast<FileWebRequest^>(WebRequest::CreateDefault( myUrl ));
         
         // Set the timeout to the value selected by the user.
         myFileWebRequest->Timeout = timeout;
         
         // Set the Method property to POST
         myFileWebRequest->Method = "POST";
         
      }
      catch ( WebException^ e ) 
      {
         Console::WriteLine( "WebException: {0}", e->Message );
      }
      catch ( UriFormatException^ e ) 
      {
         Console::WriteLine( "UriFormatWebException: {0}", e->Message );
      }

   }

   static void writeToFile()
   {
      try
      {
         
         // Enter the string to write into the file.
         Console::WriteLine( "Enter the string you want to write:" );
         String^ userInput = Console::ReadLine();
         
         // Convert the string to Byte array.
         ASCIIEncoding^ encoder = gcnew ASCIIEncoding;
         array<Byte>^byteArray = encoder->GetBytes( userInput );
         
         // Set the ContentLength property.
         myFileWebRequest->ContentLength = byteArray->Length;
         String^ contentLength = myFileWebRequest->ContentLength.ToString();
         Console::WriteLine( "\nThe content length is {0}.", contentLength );
         
         // Get the file stream handler to write into the file.
         Stream^ readStream = myFileWebRequest->GetRequestStream();
         
         // Write to the file stream.
         // Note. In order for this to work the file must be accessible
         // on the network. This can be accomplished by setting the property
         // sharing of the folder containg the file. The permissions
         // can be set so everyone can modify the file.
         // FileWebRequest::Credentials property cannot be used for this purpose.
         readStream->Write( byteArray, 0, userInput->Length );
         Console::WriteLine( "\nThe String you entered was successfully written into the file." );
         
         readStream->Close();
      }
      catch ( WebException^ e ) 
      {
         Console::WriteLine( "The WebException: {0}", e->Message );
      }
      catch ( UriFormatException^ e ) 
      {
         Console::WriteLine( "The UriFormatWebException: {0}", e->Message );
      }

   }


public:
   static void Main()
   {
      array<String^>^args = Environment::GetCommandLineArgs();
      if ( args->Length < 3 )
            showUsage();
      else
      {
         makeFileRequest( args[ 1 ], Int32::Parse( args[ 2 ] ) );
         writeToFile();
      }
   }

};

int main()
{
   TestGetRequestStream::Main();
}

// This example creates or opens a text file and stores a string in it. 
// Both the file and the string are passed by the user.
// Note. For this program to work, the folder containing the test file
// must be shared, with its permissions set to allow write access. 
using System.Net;
using System;
using System.IO;
using System.Text;

namespace Mssc.PluggableProtocols.File
{
    class TestGetRequestStream
    {
        private static FileWebRequest myFileWebRequest;

        private static void showUsage ()
        {
            Console.WriteLine ("\nPlease enter file name and timeout :");
            Console.WriteLine ("Usage: cs_getrequeststream <systemname>/<sharedfoldername>/<filename> timeout");
            Console.WriteLine ("Example: cs_getrequeststream ngetrequestrtream() ndpue/temp/hello.txt  1000");
            Console.WriteLine ("Small time-out values (for example, 3 or less) cause a time-out exception.");
        }

        private static void makeFileRequest (string fileName, int timeout)
        {
            try
            {
                // Create a Uri object. 
                Uri myUrl = new Uri ("file://" + fileName);

                // Create a FileWebRequest object.
                myFileWebRequest = (FileWebRequest)WebRequest.CreateDefault (myUrl);

                // Set the time-out to the value selected by the user.
                myFileWebRequest.Timeout = timeout;

                // Set the Method property to POST  
                myFileWebRequest.Method = "POST";
            }
            catch (WebException e)
            {
                Console.WriteLine ("WebException: " + e.Message);
            }
            catch (UriFormatException e)
            {
                Console.WriteLine ("UriFormatWebException: " + e.Message);
            }
        }

        private static void writeToFile ()
        {
            try
            {
                // Enter the string to write to the file.
                Console.WriteLine ("Enter the string you want to write:");

                string userInput = Console.ReadLine ();

                // Convert the string to a byte array.
                ASCIIEncoding encoder = new ASCIIEncoding ();
                byte[] byteArray = encoder.GetBytes (userInput);

                // Set the ContentLength property.
                myFileWebRequest.ContentLength = byteArray.Length;

                string contentLength = myFileWebRequest.ContentLength.ToString ();

                Console.WriteLine ("\nThe content length is {0}.", contentLength);

                // Get the file stream handler to write to the file.
                Stream readStream = myFileWebRequest.GetRequestStream ();

                // Write to the file stream. 
                // Note.  For this to work, the file must be accessible
                // on the network. This can be accomplished by setting the property
                // sharing of the folder containg the file. 
                // FileWebRequest.Credentials property cannot be used for this purpose.
                readStream.Write (byteArray, 0, userInput.Length);
                Console.WriteLine ("\nThe String you entered was successfully written to the file.");

                readStream.Close ();
            }
            catch (WebException e)
            {
                Console.WriteLine ("The WebException: " + e.Message);
            }
            catch (UriFormatException e)
            {
                Console.WriteLine ("The UriFormatWebException: " + e.Message);
            }
        }

        public static void Main (String[] args)
        {
            if (args.Length < 2)
                showUsage ();
            else
            {
                makeFileRequest (args[0], int.Parse (args[1]));
                writeToFile ();
            }
        }
    }
}
'
' This example creates or opens a text file and stores a string in it. 
' Both the file and the string are passed by the user.
' Note. For this program to work, the folder containing the test file
' must be shared, with its permissions set to allow write access. 

Imports System.Net
Imports System
Imports System.IO
Imports System.Text

Namespace Mssc.PluggableProtocols.File

    Module TestGetRequestStream

        Class TestGetRequestStream

            Private Shared myFileWebRequest As FileWebRequest

            ' Show how to use this program.
            Private Shared Sub showUsage()
                Console.WriteLine(ControlChars.Lf + "Please enter file name and timeout :")
                Console.WriteLine("Usage: vb_getrequeststream <systemname>/<sharedfoldername>/<filename> timeout")
                Console.WriteLine("Example: vb_getrequeststream ngetrequestrtream() ndpue/temp/hello.txt  1000")
                Console.WriteLine("Small time-out values (for example, 3 or less) cause a time-out exception.")
            End Sub

            Private Shared Sub makeFileRequest(ByVal fileName As String, ByVal timeout As Integer)
                Try
                    ' Create a Uri object.to access the file requested by the user. 
                    Dim myUrl As New Uri("file://" + fileName)

                    ' Create a FileWebRequest object.for the requeste file.
                    myFileWebRequest = CType(WebRequest.CreateDefault(myUrl), FileWebRequest)

                    ' Set the time-out to the value selected by the user.
                    myFileWebRequest.Timeout = timeout

                    ' Set the Method property to POST  
                    myFileWebRequest.Method = "POST"


                Catch e As WebException
                    Console.WriteLine(("WebException is: " + e.Message))
                Catch e As UriFormatException
                    Console.WriteLine(("UriFormatWebException is: " + e.Message))
                End Try

            End Sub

            Private Shared Sub writeToFile()
                Try
                    ' Enter the string to write to the file.
                    Console.WriteLine("Enter the string you want to write:")
                    Dim userInput As String = Console.ReadLine()

                    ' Convert the string to a byte array.
                    Dim encoder As New ASCIIEncoding
                    Dim byteArray As Byte() = encoder.GetBytes(userInput)

                    ' Set the ContentLength property.
                    myFileWebRequest.ContentLength = byteArray.Length

                    Dim contentLength As String = myFileWebRequest.ContentLength.ToString()

                    Console.WriteLine(ControlChars.Lf + "The content length is {0}.", contentLength)


                    ' Get the file stream handler to write to the file.
                    Dim readStream As Stream = myFileWebRequest.GetRequestStream()

                    ' Write to the stream. 
                    ' Note. For this to work the file must be accessible
                    ' on the network. This can be accomplished by setting the property
                    ' sharing of the folder containg the file.  
                    ' FileWebRequest.Credentials property cannot be used for this purpose.
                    readStream.Write(byteArray, 0, userInput.Length)


                    Console.WriteLine(ControlChars.Lf + "The String you entered was successfully written to the file.")

                    readStream.Close()

                Catch e As WebException
                    Console.WriteLine(("WebException is: " + e.Message))
                Catch e As UriFormatException
                    Console.WriteLine(("UriFormatWebException is: " + e.Message))
                End Try

            End Sub

            Public Shared Sub Main(ByVal args() As String)

                If args.Length < 2 Then
                    showUsage()
                Else
                    makeFileRequest(args(0), Integer.Parse(args(1)))
                    writeToFile()
                End If

            End Sub 'Main

        End Class 'TestGetRequestStream



    End Module

End Namespace

Comentarios

El FileWebRequest la clase implementa la WebRequest abstract clase base para los identificadores uniformes de recursos (URI) que usan el file:// esquema solicitar archivos locales.The FileWebRequest class implements the WebRequestabstract base class for Uniform Resource Identifiers (URIs) that use the file:// scheme to request local files.

No utilice el FileWebRequest constructor.Do not use the FileWebRequest constructor. Use la WebRequest.Create método para inicializar nuevas instancias de la FileWebRequest clase.Use the WebRequest.Create method to initialize new instances of the FileWebRequest class. Si el esquema URI es file://, Create método devuelve un FileWebRequest objeto.If the URI scheme is file://, the Create method returns a FileWebRequest object.

El GetResponse método realiza una solicitud sincrónica para el archivo especificado en el RequestUri propiedad y devuelve un FileWebResponse objeto que contiene la respuesta.The GetResponse method makes a synchronous request for the file specified in the RequestUri property and returns a FileWebResponse object that contains the response. Puede realizar una solicitud asincrónica para el archivo mediante el BeginGetResponse y EndGetResponse métodos.You can make an asynchronous request for the file using the BeginGetResponse and EndGetResponse methods.

Cuando desea escribir datos en un archivo, el GetRequestStream método devuelve un Stream instancia para escribir en.When you want to write data to a file, the GetRequestStream method returns a Stream instance to write to. El BeginGetRequestStream y EndGetRequestStream métodos proporcionan acceso asincrónico al flujo de datos de escritura.The BeginGetRequestStream and EndGetRequestStream methods provide asynchronous access to the write data stream.

El FileWebRequest clase se basa en el File clase para el control de errores y la seguridad de acceso del código.The FileWebRequest class relies on the File class for error handling and code access security.

Constructores

FileWebRequest(SerializationInfo, StreamingContext) FileWebRequest(SerializationInfo, StreamingContext) FileWebRequest(SerializationInfo, StreamingContext) FileWebRequest(SerializationInfo, StreamingContext)

Inicializa una nueva instancia de la clase FileWebRequest desde las instancias especificadas de las clases SerializationInfo y StreamingContext.Initializes a new instance of the FileWebRequest class from the specified instances of the SerializationInfo and StreamingContext classes.

Propiedades

AuthenticationLevel AuthenticationLevel AuthenticationLevel AuthenticationLevel

Obtiene o establece valores que indican el nivel de autenticación y de suplantación utilizados para esta solicitud.Gets or sets values indicating the level of authentication and impersonation used for this request.

(Inherited from WebRequest)
CachePolicy CachePolicy CachePolicy CachePolicy

Obtiene o establece la directiva de caché para esta solicitud.Gets or sets the cache policy for this request.

(Inherited from WebRequest)
ConnectionGroupName ConnectionGroupName ConnectionGroupName ConnectionGroupName

Obtiene o establece el nombre del grupo de conexiones para la solicitud.Gets or sets the name of the connection group for the request. Esta propiedad está reservada para un uso futuro.This property is reserved for future use.

ContentLength ContentLength ContentLength ContentLength

Obtiene o establece la longitud del contenido de los datos que se envían.Gets or sets the content length of the data being sent.

ContentType ContentType ContentType ContentType

Obtiene o establece el tipo de contenido de los datos que se envían.Gets or sets the content type of the data being sent. Esta propiedad está reservada para un uso futuro.This property is reserved for future use.

CreatorInstance CreatorInstance CreatorInstance CreatorInstance

Cuando se reemplaza en una clase descendiente, obtiene el objeto generador derivado de la clase IWebRequestCreate usada para crear la instancia de WebRequest para efectuar la solicitud al URI especificado.When overridden in a descendant class, gets the factory object derived from the IWebRequestCreate class used to create the WebRequest instantiated for making the request to the specified URI.

(Inherited from WebRequest)
Credentials Credentials Credentials Credentials

Obtiene o establece las credenciales asociadas a esta solicitud.Gets or sets the credentials that are associated with this request. Esta propiedad está reservada para un uso futuro.This property is reserved for future use.

Headers Headers Headers Headers

Obtiene una colección de los pares de nombre y valor asociados a la solicitud.Gets a collection of the name/value pairs that are associated with the request. Esta propiedad está reservada para un uso futuro.This property is reserved for future use.

ImpersonationLevel ImpersonationLevel ImpersonationLevel ImpersonationLevel

Obtiene o establece el nivel de suplantación para la solicitud actual.Gets or sets the impersonation level for the current request.

(Inherited from WebRequest)
Method Method Method Method

Obtiene o establece el método de protocolo utilizado para realizar la solicitud.Gets or sets the protocol method used for the request. Esta propiedad está reservada para un uso futuro.This property is reserved for future use.

PreAuthenticate PreAuthenticate PreAuthenticate PreAuthenticate

Obtiene o establece un valor que indica si se va a realizar la autenticación previa de una solicitud.Gets or sets a value that indicates whether to preauthenticate a request. Esta propiedad está reservada para un uso futuro.This property is reserved for future use.

Proxy Proxy Proxy Proxy

Obtiene o establece el proxy de red que se va a utilizar para esta solicitud.Gets or sets the network proxy to use for this request. Esta propiedad está reservada para un uso futuro.This property is reserved for future use.

RequestUri RequestUri RequestUri RequestUri

Obtiene el identificador uniforme de recursos (URI) de la solicitud.Gets the Uniform Resource Identifier (URI) of the request.

Timeout Timeout Timeout Timeout

Obtiene o establece el tiempo que transcurre hasta que se agota el tiempo de espera de la solicitud.Gets or sets the length of time until the request times out.

UseDefaultCredentials UseDefaultCredentials UseDefaultCredentials UseDefaultCredentials

Siempre inicia una NotSupportedException.Always throws a NotSupportedException.

Métodos

Abort() Abort() Abort() Abort()

Cancela una solicitud de un recurso de Internet.Cancels a request to an Internet resource.

BeginGetRequestStream(AsyncCallback, Object) BeginGetRequestStream(AsyncCallback, Object) BeginGetRequestStream(AsyncCallback, Object) BeginGetRequestStream(AsyncCallback, Object)

Inicia una solicitud asincrónica de un objeto Stream que se va a utilizar para escribir datos.Begins an asynchronous request for a Stream object to use to write data.

BeginGetResponse(AsyncCallback, Object) BeginGetResponse(AsyncCallback, Object) BeginGetResponse(AsyncCallback, Object) BeginGetResponse(AsyncCallback, Object)

Inicia una solicitud asincrónica de un recurso del sistema de archivos.Begins an asynchronous request for a file system resource.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
EndGetRequestStream(IAsyncResult) EndGetRequestStream(IAsyncResult) EndGetRequestStream(IAsyncResult) EndGetRequestStream(IAsyncResult)

Finaliza una solicitud asincrónica de una instancia de Stream que la aplicación usa para escribir datos.Ends an asynchronous request for a Stream instance that the application uses to write data.

EndGetResponse(IAsyncResult) EndGetResponse(IAsyncResult) EndGetResponse(IAsyncResult) EndGetResponse(IAsyncResult)

Termina una solicitud asincrónica de un recurso del sistema de archivos.Ends an asynchronous request for a file system resource.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

Llena SerializationInfo con los datos necesarios para serializar el objeto de destino.Populates a SerializationInfo with the data needed to serialize the target object.

GetRequestStream() GetRequestStream() GetRequestStream() GetRequestStream()

Devuelve un objeto Stream para escribir datos en el recurso del sistema de archivos.Returns a Stream object for writing data to the file system resource.

GetRequestStreamAsync() GetRequestStreamAsync() GetRequestStreamAsync() GetRequestStreamAsync()

Cuando se invalida en una clase descendiente, devuelve un objeto Stream para escribir datos en el recurso de Internet como una operación asincrónica.When overridden in a descendant class, returns a Stream for writing data to the Internet resource as an asynchronous operation.

(Inherited from WebRequest)
GetResponse() GetResponse() GetResponse() GetResponse()

Devuelve una respuesta a una solicitud del sistema de archivos.Returns a response to a file system request.

GetResponseAsync() GetResponseAsync() GetResponseAsync() GetResponseAsync()

Cuando se invalida en una clase descendiente, devuelve una respuesta a una solicitud de Internet como una operación asincrónica.When overridden in a descendant class, returns a response to an Internet request as an asynchronous operation.

(Inherited from WebRequest)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Implementaciones de interfaz explícitas

ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Rellena un objeto SerializationInfo con los datos necesarios para serializar FileWebRequest.Populates a SerializationInfo object with the required data to serialize the FileWebRequest.

Se aplica a

Consulte también: