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 체계를 WebRequest abstract 사용하여 file:// 로컬 파일을 요청하는 URI(Uniform Resource Identifiers)에 대한 기본 클래스를 구현합니다.

생성자를 사용하지 FileWebRequest 마세요. 메서드를 WebRequest.Create 사용하여 클래스의 FileWebRequest 새 인스턴스를 초기화합니다. URI 체계인 경우 메서드는 file://Create 개체를 반환합니다FileWebRequest.

메서드는 GetResponse 속성에 지정된 RequestUri 파일에 대해 동기 요청을 수행하고 응답이 포함된 개체를 반환 FileWebResponse 합니다. 및 EndGetResponse 메서드를 사용하여 BeginGetResponse 파일에 대한 비동기 요청을 만들 수 있습니다.

파일에 데이터를 쓰려는 경우 메서드는 GetRequestStream 쓸 인스턴스를 Stream 반환합니다. 및 EndGetRequestStream 메서드는 BeginGetRequestStream 쓰기 데이터 스트림에 대한 비동기 액세스를 제공합니다.

클래스는 FileWebRequest 오류 처리 및 코드 액세스 보안을 위해 클래스를 File 사용합니다.

생성자

FileWebRequest(SerializationInfo, StreamingContext)
사용되지 않습니다.
사용되지 않습니다.
사용되지 않습니다.

FileWebRequestSerializationInfo 클래스에 지정된 인스턴스에서 StreamingContext 클래스의 새 인스턴스를 초기화합니다.

속성

AuthenticationLevel

이 요청에 사용되는 인증 및 가장 수준을 나타내는 값을 가져오거나 설정합니다.

(다음에서 상속됨 WebRequest)
CachePolicy

이 요청에 대한 캐시 정책을 가져오거나 설정합니다.

(다음에서 상속됨 WebRequest)
ConnectionGroupName

요청에 대한 연결 그룹의 이름을 가져오거나 설정합니다. 이 속성은 나중에 사용할 수 있도록 예약됩니다.

ContentLength

보내고 있는 데이터의 콘텐츠 길이를 가져오거나 설정합니다.

ContentType

보내고 있는 데이터의 콘텐츠 형식을 가져오거나 설정합니다. 이 속성은 나중에 사용할 수 있도록 예약됩니다.

CreatorInstance
사용되지 않습니다.

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

(다음에서 상속됨 WebRequest)
Credentials

이 요청과 관련된 자격 증명을 가져오거나 설정합니다. 이 속성은 나중에 사용할 수 있도록 예약됩니다.

Headers

요청과 관련된 이름/값 쌍의 컬렉션을 가져옵니다. 이 속성은 나중에 사용할 수 있도록 예약됩니다.

ImpersonationLevel

현재 요청에 대한 가장 수준을 가져오거나 설정합니다.

(다음에서 상속됨 WebRequest)
Method

요청하는 데 사용되는 프로토콜 메서드를 가져오거나 설정합니다. 이 속성은 나중에 사용할 수 있도록 예약됩니다.

PreAuthenticate

요청을 미리 인증하는지 여부를 나타내는 값을 가져오거나 설정합니다. 이 속성은 나중에 사용할 수 있도록 예약됩니다.

Proxy

이 요청에 사용할 네트워크 프록시를 가져오거나 설정합니다. 이 속성은 나중에 사용할 수 있도록 예약됩니다.

RequestUri

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

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를 serialize하는 데 필요한 데이터로 FileWebRequest 개체를 채웁니다.

적용 대상

추가 정보