FileWebRequest 類別

定義

提供 WebRequest 類別的檔案系統實作。Provides a file system implementation of the WebRequest class.

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 類別來存取檔案系統資源。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 會針對使用 file:// 配置來要求本機檔案的 (Uri) ,為統一資源識別項實作為基底類別。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 可以使用方法來初始化類別的新實例 FileWebRequestUse 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. 您可以使用和方法,對檔案進行非同步要求 BeginGetResponse EndGetResponseYou 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 類別的新執行個體,這個執行個體是來自 SerializationInfoStreamingContext 類別的指定執行個體。Initializes a new instance of the FileWebRequest class from the specified instances of the SerializationInfo and StreamingContext classes.

屬性

AuthenticationLevel

取得或設定值,指出用於這個要求的驗證和模擬等級。Gets or sets values indicating the level of authentication and impersonation used for this request.

(繼承來源 WebRequest)
CachePolicy

取得或設定這個要求的快取原則。Gets or sets the cache policy for this request.

(繼承來源 WebRequest)
ConnectionGroupName

取得或設定要求的連線群組名稱。Gets or sets the name of the connection group for the request. 這個屬性保留給未來的版本使用。This property is reserved for future use.

ContentLength

取得或設定正在傳送之資料的內容長度。Gets or sets the content length of the data being sent.

ContentType

取得或設定正在傳送之資料的內容類型。Gets or sets the content type of the data being sent. 這個屬性保留給未來的版本使用。This property is reserved for future use.

CreatorInstance
已過時。

在子代類別中覆寫時,取得衍生自 IWebRequestCreate 類別的 Factory 物件,用來建立執行個體化的 WebRequest 以對指定的 URI 提出要求。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.

(繼承來源 WebRequest)
Credentials

取得或設定與這個要求關聯的認證。Gets or sets the credentials that are associated with this request. 這個屬性保留給未來的版本使用。This property is reserved for future use.

Headers

取得與要求關聯的名稱/值組的集合。Gets a collection of the name/value pairs that are associated with the request. 這個屬性保留給未來的版本使用。This property is reserved for future use.

ImpersonationLevel

取得或設定目前要求的模擬等級。Gets or sets the impersonation level for the current request.

(繼承來源 WebRequest)
Method

取得或設定要求所使用的通訊協定 (Protocol) 方法。Gets or sets the protocol method used for the request. 這個屬性保留給未來的版本使用。This property is reserved for future use.

PreAuthenticate

取得或設定值,指示是否要預先驗證要求。Gets or sets a value that indicates whether to preauthenticate a request. 這個屬性保留給未來的版本使用。This property is reserved for future use.

Proxy

取得或設定這個要求所使用的網路 Proxy。Gets or sets the network proxy to use for this request. 這個屬性保留給未來的版本使用。This property is reserved for future use.

RequestUri

取得要求的統一資源識別元 (URI)。Gets the Uniform Resource Identifier (URI) of the request.

Timeout

取得或設定要求逾時之前的時間長度。Gets or sets the length of time until the request times out.

UseDefaultCredentials

永遠擲回 NotSupportedExceptionAlways throws a NotSupportedException.

UseDefaultCredentials

在子代類別中覆寫時,取得或設定 Boolean 值,控制 DefaultCredentials 是否隨著要求傳送。When overridden in a descendant class, gets or sets a Boolean value that controls whether DefaultCredentials are sent with requests.

(繼承來源 WebRequest)

方法

Abort()

取消對網際網路資源的要求。Cancels a request to an Internet resource.

Abort()

中止要求。Aborts the request.

(繼承來源 WebRequest)
BeginGetRequestStream(AsyncCallback, Object)

開始用以寫入資料之 Stream 物件的非同步要求。Begins an asynchronous request for a Stream object to use to write data.

BeginGetResponse(AsyncCallback, Object)

開始檔案系統資源的非同步要求。Begins an asynchronous request for a file system resource.

CreateObjRef(Type)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(繼承來源 MarshalByRefObject)
EndGetRequestStream(IAsyncResult)

結束應用程式用來寫入資料之 Stream 執行個體的非同步要求。Ends an asynchronous request for a Stream instance that the application uses to write data.

EndGetResponse(IAsyncResult)

結束檔案系統資源的非同步要求。Ends an asynchronous request for a file system resource.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetLifetimeService()
已過時。

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)
GetObjectData(SerializationInfo, StreamingContext)

將序列化目標物件所需的資料填入 SerializationInfoPopulates a SerializationInfo with the data needed to serialize the target object.

GetObjectData(SerializationInfo, StreamingContext)

將序列化目標物件所需的資料填入 SerializationInfoPopulates a SerializationInfo with the data needed to serialize the target object.

(繼承來源 WebRequest)
GetRequestStream()

傳回 Stream 物件,用於將資料寫入至檔案系統資源。Returns a Stream object for writing data to the file system resource.

GetRequestStreamAsync()

以非同步作業的方式傳回資料流,將資料寫入檔案系統資源。Returns a stream for writing data to the file system resource as an asynchronous operation.

GetRequestStreamAsync()

在子代類別中覆寫時,傳回以非同步作業方式將資料寫入網際網路資源的 StreamWhen overridden in a descendant class, returns a Stream for writing data to the Internet resource as an asynchronous operation.

(繼承來源 WebRequest)
GetResponse()

傳回對檔案系統要求的回應。Returns a response to a file system request.

GetResponseAsync()

以非同步作業方式傳回檔案系統要求的回應。Returns a response to a file system request as an asynchronous operation.

GetResponseAsync()

在子代類別中覆寫時,傳回對網際網路要求的回應,做為非同步作業。When overridden in a descendant class, returns a response to an Internet request as an asynchronous operation.

(繼承來源 WebRequest)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
InitializeLifetimeService()
已過時。

取得存留期服務物件,以控制這個執行個體的存留期原則。Obtains a lifetime service object to control the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)
MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
MemberwiseClone(Boolean)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(繼承來源 MarshalByRefObject)
ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

明確介面實作

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

將序列化 SerializationInfo 所需的資料,填入 FileWebRequest 物件。Populates a SerializationInfo object with the required data to serialize the FileWebRequest.

適用於

另請參閱