FileWebRequest FileWebRequest FileWebRequest FileWebRequest Class

정의

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
상속
특성
구현

예제

다음 코드 예제에서는 FileWebRequest 파일 시스템 리소스에 액세스 하는 클래스입니다.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.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 클래스가 구현 하는 WebRequest abstract 를 사용 하는 Uniform Resource Identifier (Uri)에 대 한 기본 클래스를 file:// 로컬 파일을 요청 하는 스키마.The FileWebRequest class implements the WebRequestabstract base class for Uniform Resource Identifiers (URIs) that use the file:// scheme to request local files.

사용 하지 마십시오는 FileWebRequest 생성자입니다.Do not use the FileWebRequest constructor. 사용 된 WebRequest.Create 의 새 인스턴스를 초기화 하는 방법의 FileWebRequest 클래스.Use the WebRequest.Create method to initialize new instances of the FileWebRequest class. URI 구성표가 인 경우 file://, Create 메서드가 반환 되는 FileWebRequest 개체입니다.If the URI scheme is file://, the Create method returns a FileWebRequest object.

GetResponse 에 지정 된 파일에 대 한 동기 요청을 수행 하는 메서드를 RequestUri 속성과 반환을 FileWebResponse 응답이 들어 있는 개체입니다.The GetResponse method makes a synchronous request for the file specified in the RequestUri property and returns a FileWebResponse object that contains the response. 사용 하 여 파일에 대 한 비동기 요청을 할 수 있습니다 합니다 BeginGetResponseEndGetResponse 메서드.You can make an asynchronous request for the file using the BeginGetResponse and EndGetResponse methods.

파일에 데이터를 작성 하려는 경우는 GetRequestStream 메서드가 반환 되는 Stream 쓸 인스턴스.When you want to write data to a file, the GetRequestStream method returns a Stream instance to write to. 합니다 BeginGetRequestStreamEndGetRequestStream 메서드 쓰기 데이터 스트림에 대 한 비동기 액세스를 제공 합니다.The BeginGetRequestStream and EndGetRequestStream methods provide asynchronous access to the write data stream.

합니다 FileWebRequest 클래스에 의존 합니다 File 오류 처리 및 코드 액세스 보안에 대 한 클래스입니다.The FileWebRequest class relies on the File class for error handling and code access security.

생성자

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

FileWebRequestSerializationInfo 클래스에 지정된 인스턴스에서 StreamingContext 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the FileWebRequest class from the specified instances of the SerializationInfo and StreamingContext classes.

속성

AuthenticationLevel AuthenticationLevel AuthenticationLevel AuthenticationLevel

이 요청에 사용되는 인증 및 가장 수준을 나타내는 값을 가져오거나 설정합니다.Gets or sets values indicating the level of authentication and impersonation used for this request.

(Inherited from WebRequest)
CachePolicy CachePolicy CachePolicy CachePolicy

이 요청에 대한 캐시 정책을 가져오거나 설정합니다.Gets or sets the cache policy for this request.

(Inherited from WebRequest)
ConnectionGroupName ConnectionGroupName ConnectionGroupName ConnectionGroupName

요청에 대한 연결 그룹의 이름을 가져오거나 설정합니다.Gets or sets the name of the connection group for the request. 이 속성은 나중에 사용할 수 있도록 예약됩니다.This property is reserved for future use.

ContentLength ContentLength ContentLength ContentLength

보내고 있는 데이터의 콘텐츠 길이를 가져오거나 설정합니다.Gets or sets the content length of the data being sent.

ContentType ContentType ContentType ContentType

보내고 있는 데이터의 콘텐츠 형식을 가져오거나 설정합니다.Gets or sets the content type of the data being sent. 이 속성은 나중에 사용할 수 있도록 예약됩니다.This property is reserved for future use.

CreatorInstance CreatorInstance CreatorInstance CreatorInstance

하위 클래스에서 재정의될 때, 지정된 URI 에 요청하기 위해 인스턴스화된 WebRequest를 만드는 데 사용되는 IWebRequestCreate 클래스에서 파생된 팩터리 개체를 가져옵니다.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

이 요청과 관련된 자격 증명을 가져오거나 설정합니다.Gets or sets the credentials that are associated with this request. 이 속성은 나중에 사용할 수 있도록 예약됩니다.This property is reserved for future use.

Headers Headers Headers Headers

요청과 관련된 이름/값 쌍의 컬렉션을 가져옵니다.Gets a collection of the name/value pairs that are associated with the request. 이 속성은 나중에 사용할 수 있도록 예약됩니다.This property is reserved for future use.

ImpersonationLevel ImpersonationLevel ImpersonationLevel ImpersonationLevel

현재 요청에 대한 가장 수준을 가져오거나 설정합니다.Gets or sets the impersonation level for the current request.

(Inherited from WebRequest)
Method Method Method Method

요청하는 데 사용되는 프로토콜 메서드를 가져오거나 설정합니다.Gets or sets the protocol method used for the request. 이 속성은 나중에 사용할 수 있도록 예약됩니다.This property is reserved for future use.

PreAuthenticate PreAuthenticate PreAuthenticate PreAuthenticate

요청을 미리 인증하는지 여부를 나타내는 값을 가져오거나 설정합니다.Gets or sets a value that indicates whether to preauthenticate a request. 이 속성은 나중에 사용할 수 있도록 예약됩니다.This property is reserved for future use.

Proxy Proxy Proxy Proxy

이 요청에 사용할 네트워크 프록시를 가져오거나 설정합니다.Gets or sets the network proxy to use for this request. 이 속성은 나중에 사용할 수 있도록 예약됩니다.This property is reserved for future use.

RequestUri RequestUri RequestUri RequestUri

요청의 URI(Uniform Resource Identifier)를 가져옵니다.Gets the Uniform Resource Identifier (URI) of the request.

Timeout Timeout Timeout Timeout

요청 시간이 초과될 때까지의 시간을 가져오거나 설정합니다.Gets or sets the length of time until the request times out.

UseDefaultCredentials UseDefaultCredentials UseDefaultCredentials UseDefaultCredentials

항상 NotSupportedException을 throw합니다.Always throws a NotSupportedException.

메서드

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

인터넷 리소스에 대한 요청을 취소합니다.Cancels a request to an Internet resource.

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

데이터를 쓰는 데 사용할 Stream 개체에 대한 비동기 요청을 시작합니다.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)

파일 시스템 리소스에 대한 비동기 요청을 시작합니다.Begins an asynchronous request for a file system resource.

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

원격 개체와 통신하는 데 사용되는 프록시 생성에 필요한 모든 관련 정보가 들어 있는 개체를 만듭니다.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)

애플리케이션이 데이터를 쓰는 데 사용하는 Stream 인스턴스에 대한 비동기 요청을 종료합니다.Ends an asynchronous request for a Stream instance that the application uses to write data.

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

파일 시스템 리소스에 대한 비동기 요청을 종료합니다.Ends an asynchronous request for a file system resource.

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

지정한 개체와 현재 개체가 같은지 여부를 확인합니다.Determines whether the specified object is equal to the current object.

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

기본 해시 함수로 작동합니다.Serves as the default hash function.

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

이 인스턴스의 수명 정책을 제어하는 현재의 수명 서비스 개체를 검색합니다.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)

대상 개체를 직렬화하는 데 필요한 데이터로 SerializationInfo를 채웁니다.Populates a SerializationInfo with the data needed to serialize the target object.

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

파일 시스템 리소스에 데이터를 쓰기 위한 Stream 개체를 반환합니다.Returns a Stream object for writing data to the file system resource.

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

데이터를 파일 시스템 리소스에 쓰기 위해 스트림을 비동기 작업으로 반환합니다.Returns a stream for writing data to the file system resource as an asynchronous operation.

GetResponse() GetResponse() GetResponse() GetResponse()

파일 시스템 요청에 대한 응답을 반환합니다.Returns a response to a file system request.

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

파일 시스템 요청에 대한 응답을 비동기 작업으로 반환합니다.Returns a response to a file system request as an asynchronous operation.

GetType() GetType() GetType() GetType()

현재 인스턴스의 Type을 가져옵니다.Gets the Type of the current instance.

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

이 인스턴스의 수명 정책을 제어하는 수명 서비스 개체를 가져옵니다.Obtains a lifetime service object to control the lifetime policy for this instance.

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

현재 Object의 단순 복사본을 만듭니다.Creates a shallow copy of the current Object.

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

현재 MarshalByRefObject 개체의 단순 복사본을 만듭니다.Creates a shallow copy of the current MarshalByRefObject object.

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

현재 개체를 나타내는 문자열을 반환합니다.Returns a string that represents the current object.

(Inherited from Object)

명시적 인터페이스 구현

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

SerializationInfo를 serialize하는 데 필요한 데이터로 FileWebRequest 개체를 채웁니다.Populates a SerializationInfo object with the required data to serialize the FileWebRequest.

적용 대상

추가 정보