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
已过时.

在后代类中重写时,获取派生自 IWebRequestCreate 类的工厂对象,该类用于创建实例化 WebRequest,以便向指定的 URI 发出请求。

(继承自 WebRequest)
Credentials

获取或设置与此请求关联的凭据。 此属性保留供将来使用。

Headers

获取与请求关联的名称/值对的集合。 此属性保留供将来使用。

ImpersonationLevel

获取或设置当前请求的模拟级别。

(继承自 WebRequest)
Method

获取或设置用于请求的协议方法。 此属性保留供将来使用。

PreAuthenticate

获取或设置一个值,该值指示是否预身份验证请求。 此属性保留供将来使用。

Proxy

获取或设置要用于此请求的网络代理。 此属性保留供将来使用。

RequestUri

获取请求的统一资源标识符(URI)。

Timeout

获取或设置请求超时之前的时间长度。

UseDefaultCredentials

始终引发 NotSupportedException

UseDefaultCredentials

在后代类中重写时,获取或设置一个 Boolean 值,该值控制是否使用请求发送 DefaultCredentials

(继承自 WebRequest)

方法

Abort()

取消对 Internet 资源的请求。

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,用于将数据作为异步操作写入 Internet 资源。

(继承自 WebRequest)
GetResponse()

返回对文件系统请求的响应。

GetResponseAsync()

以异步操作的形式返回对文件系统请求的响应。

GetResponseAsync()

在后代类中重写时,以异步操作的形式返回对 Internet 请求的响应。

(继承自 WebRequest)
GetType()

获取当前实例的 Type

(继承自 Object)
InitializeLifetimeService()
已过时.

获取生存期服务对象来控制此实例的生存期策略。

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。

(继承自 MarshalByRefObject)
ToString()

返回一个表示当前对象的字符串。

(继承自 Object)

显式接口实现

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
已过时.

使用序列化 FileWebRequest所需的数据填充 SerializationInfo 对象。

适用于

另请参阅