FileWebRequest.GetRequestStream 方法

定義

傳回 Stream 物件,用於將資料寫入至檔案系統資源。

C#
public override System.IO.Stream GetRequestStream();

傳回

Stream,用於將資料寫入至檔案系統資源。

例外狀況

要求逾時。

範例

下列程式代碼範例會 GetRequestStream 使用 方法來取得用來寫入檔案的數據流實例。 請參閱 類別 FileWebRequest 中的完整範例。

C#
// 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.");

備註

方法 GetRequestStream 會提供 對的 Stream同步存取。 針對異步存取,請使用 BeginGetRequestStreamEndGetRequestStream 方法。

適用於

產品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

另請參閱