FileWebRequest Класс

Определение

Предоставляет реализацию файловой системы класса WebRequest.

public ref class FileWebRequest : System::Net::WebRequest, System::Runtime::Serialization::ISerializable
public ref class FileWebRequest : System::Net::WebRequest
public class FileWebRequest : System.Net.WebRequest, System.Runtime.Serialization.ISerializable
[System.Serializable]
public class FileWebRequest : System.Net.WebRequest, System.Runtime.Serialization.ISerializable
public class FileWebRequest : System.Net.WebRequest
type FileWebRequest = class
    inherit WebRequest
    interface ISerializable
[<System.Serializable>]
type FileWebRequest = class
    inherit WebRequest
    interface ISerializable
Public Class FileWebRequest
Inherits WebRequest
Implements ISerializable
Public Class FileWebRequest
Inherits WebRequest
Наследование
Атрибуты
Реализации

Примеры

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

// 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.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

        End Class



    End Module

End Namespace

Комментарии

Класс FileWebRequest реализует базовый WebRequestabstract класс для универсальных идентификаторов ресурсов (URI), которые используют схему file:// для запроса локальных файлов.

Не используйте FileWebRequest конструктор . Используйте метод для инициализации WebRequest.Create новых экземпляров FileWebRequest класса . Если схема URI имеет значение file://, Create метод возвращает FileWebRequest объект .

Метод GetResponse выполняет синхронный запрос к файлу, указанному в свойстве RequestUri , и возвращает FileWebResponse объект, содержащий ответ. Вы можете выполнить асинхронный запрос к файлу с помощью BeginGetResponse методов и EndGetResponse .

Если требуется записать данные в файл, GetRequestStream метод возвращает Stream экземпляр для записи. Методы BeginGetRequestStream и EndGetRequestStream предоставляют асинхронный доступ к потоку данных записи.

Класс FileWebRequest использует класс для File обработки ошибок и обеспечения безопасности доступа к коду.

Конструкторы

FileWebRequest(SerializationInfo, StreamingContext)
Устаревшие..
Устаревшие..
Устаревшие..

Инициализирует новый экземпляр класса FileWebRequest на основе указанных экземпляров классов SerializationInfo и StreamingContext.

Свойства

AuthenticationLevel

Возвращает или задает значения, указывающие уровень проверки подлинности и олицетворения, используемые для этого запроса.

(Унаследовано от WebRequest)
CachePolicy

Возвращает или задает политику кэширования для этого запроса.

(Унаследовано от WebRequest)
ConnectionGroupName

Возвращает или задает имя группы подключения для запроса. Это свойство зарезервировано для дальнейшего использования.

ContentLength

Возвращает или задает длину содержимого отправляемых данных.

ContentType

Возвращает или задает тип содержимого отправляемых данных. Это свойство зарезервировано для дальнейшего использования.

CreatorInstance
Устаревшие..

Если переопределено в производном классе, получает объект фабрики, производный от класса IWebRequestCreate, который служит для создания объекта WebRequest для создания запроса по указанному универсальному коду ресурса (URI).

(Унаследовано от WebRequest)
Credentials

Возвращает или устанавливает учетные данные, связанные с этим запросом. Это свойство зарезервировано для дальнейшего использования.

Headers

Возвращает или задает коллекцию пар "имя-значение", связанных с запросом. Это свойство зарезервировано для дальнейшего использования.

ImpersonationLevel

Возвращает или задает уровень олицетворения для текущего запроса.

(Унаследовано от WebRequest)
Method

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

PreAuthenticate

Возвращает или задает значение, показывающее, необходимо ли выполнять предварительную проверку подлинности запроса. Это свойство зарезервировано для дальнейшего использования.

Proxy

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

RequestUri

Возвращает URI этого запроса.

Timeout

Возвращает или задает срок действия запроса.

UseDefaultCredentials

Всегда создает исключение NotSupportedException.

UseDefaultCredentials

Если переопределено во вложенном классе, возвращает или задает значение Boolean, с помощью которого определяется, следует ли отправлять учетные данные DefaultCredentials вместе с запросами.

(Унаследовано от WebRequest)

Методы

Abort()

Отменяет запрос к интернет-ресурсу.

Abort()

Отменяет запрос.

(Унаследовано от WebRequest)
BeginGetRequestStream(AsyncCallback, Object)

Начинает асинхронный запрос объекта Stream, используемого для записи данных.

BeginGetResponse(AsyncCallback, Object)

Начинает асинхронный запрос ресурса файловой системы.

CreateObjRef(Type)

Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом.

(Унаследовано от MarshalByRefObject)
EndGetRequestStream(IAsyncResult)

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

EndGetResponse(IAsyncResult)

Завершает асинхронный запрос ресурса файловой системы.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetLifetimeService()
Устаревшие..

Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра.

(Унаследовано от MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)
Устаревшие..

Заполняет объект SerializationInfo данными, необходимыми для сериализации целевого объекта.

GetObjectData(SerializationInfo, StreamingContext)
Устаревшие..

Заполняет объект SerializationInfo данными, необходимыми для сериализации целевого объекта.

(Унаследовано от WebRequest)
GetRequestStream()

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

GetRequestStreamAsync()

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

GetRequestStreamAsync()

Если переопределено во вложенном классе, возвращает Stream для записи данных в интернет-ресурс в ходе асинхронной операции.

(Унаследовано от WebRequest)
GetResponse()

Возвращает ответ на запрос файловой системы.

GetResponseAsync()

Возвращает ответ на запрос файловой системы в качестве асинхронной операции.

GetResponseAsync()

При переопределении во вложенном классе возвращает ответ на интернет-запрос в виде асинхронной операции.

(Унаследовано от WebRequest)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
InitializeLifetimeService()
Устаревшие..

Получает объект службы времени существования для управления политикой времени существования для этого экземпляра.

(Унаследовано от MarshalByRefObject)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
MemberwiseClone(Boolean)

Создает неполную копию текущего объекта MarshalByRefObject.

(Унаследовано от MarshalByRefObject)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
Устаревшие..

Передает объекту SerializationInfo данные, необходимые для сериализации объекта FileWebRequest.

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

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