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 'TestGetRequestStream



    End Module

End Namespace

注解

类实现使用方案请求本地文件的统一资源标识符(uri)的基类。abstract file:// WebRequest FileWebRequestThe 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. 使用方法初始化FileWebRequest类的新实例。 WebRequest.CreateUse 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.

方法对RequestUri属性中指定的文件进行同步请求, 并返回FileWebResponse包含响应的对象。 GetResponseThe 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

当在子类中重写时,获取从 IWebRequestCreate 类派生的工厂对象,该类用于创建为生成对指定 URI 的请求而实例化的 WebRequestWhen 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)。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

总是引发 NotSupportedExceptionAlways throws a NotSupportedException.

方法

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

取消对 Internet 资源的请求。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)

使用将目标对象序列化所需的数据填充 SerializationInfoPopulates 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()

获取当前实例的 TypeGets 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 所需的数据来填充 FileWebRequest 对象。Populates a SerializationInfo object with the required data to serialize the FileWebRequest.

适用于

另请参阅