共用方式為


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 類別會針對使用 file:// 配置要求本機檔案的統一資源標識碼 (URI) 實作 WebRequestabstract 基類。

請勿使用 FileWebRequest 建構函式。 使用 WebRequest.Create 方法來初始化 FileWebRequest 類別的新實例。 如果 URI 配置是 file://,則 Create 方法會傳回 FileWebRequest 物件。

GetResponse 方法會針對在 RequestUri 屬性中指定的檔案提出同步要求,並傳回包含回應的 FileWebResponse 物件。 您可以使用 BeginGetResponseEndGetResponse 方法來對檔案提出異步要求。

當您想要將數據寫入檔案時,GetRequestStream 方法會傳回要寫入的 Stream 實例。 BeginGetRequestStreamEndGetRequestStream 方法會提供寫入數據流的異步存取。

FileWebRequest 類別依賴 File 類別來處理錯誤和程式代碼存取安全性。

建構函式

FileWebRequest(SerializationInfo, StreamingContext)
已淘汰.
已淘汰.
已淘汰.

SerializationInfoStreamingContext 類別的指定實例,初始化 FileWebRequest 類別的新實例。

屬性

AuthenticationLevel

取得或設定值,指出用於這個要求的驗證和模擬層級。

(繼承來源 WebRequest)
CachePolicy

取得或設定這個要求的快取原則。

(繼承來源 WebRequest)
ConnectionGroupName

取得或設定要求的連接組名。 此屬性保留供日後使用。

ContentLength

取得或設定所傳送數據的內容長度。

ContentType

取得或設定要傳送之數據的內容類型。 此屬性保留供日後使用。

CreatorInstance
已淘汰.

在子代類別中覆寫時,取得衍生自用來建立 WebRequest 具現化之要求至指定 URI IWebRequestCreate 類別的 Factory 物件。

(繼承來源 WebRequest)
Credentials

取得或設定與此要求相關聯的認證。 此屬性保留供日後使用。

Headers

取得與要求相關聯的名稱/值組集合。 此屬性保留供日後使用。

ImpersonationLevel

取得或設定目前要求的模擬層級。

(繼承來源 WebRequest)
Method

取得或設定用於要求的通訊協定方法。 此屬性保留供日後使用。

PreAuthenticate

取得或設定值,這個值表示是否要預先驗證要求。 此屬性保留供日後使用。

Proxy

取得或設定要用於此要求的網路 Proxy。 此屬性保留供日後使用。

RequestUri

取得要求的統一資源標識碼(URI)。

Timeout

取得或設定要求逾時為止的時間長度。

UseDefaultCredentials

一律會擲回 NotSupportedException

UseDefaultCredentials

在子代類別中覆寫時,取得或設定 Boolean 值,控制是否以要求傳送 DefaultCredentials

(繼承來源 WebRequest)

方法

Abort()

取消對因特網資源的要求。

Abort()

中止要求。

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

開始異步要求,讓 Stream 對象用來寫入數據。

BeginGetResponse(AsyncCallback, Object)

開始文件系統資源的異步要求。

CreateObjRef(Type)

建立物件,其中包含產生用來與遠端物件通訊之 Proxy 所需的所有相關信息。

(繼承來源 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)
已淘汰.

使用串行化 FileWebRequest的必要數據填入 SerializationInfo 物件。

適用於

另請參閱