FileInfo.OpenWrite 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
建立一個唯寫 FileStream。
public:
System::IO::FileStream ^ OpenWrite();
public System.IO.FileStream OpenWrite();
member this.OpenWrite : unit -> System.IO.FileStream
Public Function OpenWrite () As FileStream
傳回
一個只寫入且未共享 FileStream 的物件,用於新檔案或現有檔案。
例外狀況
建立物件實例 FileInfo 時指定的路徑是唯讀或為目錄。
建立物件實例 FileInfo 時指定的路徑是無效的,例如位於未映射的磁碟機上。
範例
以下範例會打開一個檔案進行寫入,然後從該檔案讀取。
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c:\Temp\MyTest.txt";
FileInfo fi = new FileInfo(path);
// Open the stream for writing.
using (FileStream fs = fi.OpenWrite())
{
Byte[] info =
new UTF8Encoding(true).GetBytes("This is to test the OpenWrite method.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
// Open the stream and read it back.
using (FileStream fs = fi.OpenRead())
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b,0,b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
}
}
//This code produces output similar to the following;
//This is to test the OpenWrite method.
Imports System.IO
Imports System.Text
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\Temp\MyTest.txt"
Dim fi As FileInfo = New FileInfo(path)
Dim fs As FileStream
' Open the stream for writing.
fs = fi.OpenWrite()
Dim info As Byte() = _
New UTF8Encoding(True).GetBytes("This is to test the OpenWrite method.")
' Add some information to the file.
fs.Write(info, 0, info.Length)
fs.Close()
'Open the stream and read it back.
fs = fi.OpenRead()
Dim b(1023) As Byte
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Do While fs.Read(b, 0, b.Length) > 0
Console.WriteLine(temp.GetString(b))
Loop
fs.Close()
End Sub
End Class
'This code produces output similar to the following;
'results may vary based on the computer/file structure/etc.:
'
'This is to test the OpenWrite method.
'
'
'
'
'
'
'
'
'
'
'
'
備註
若該路徑已有檔案,則 OpenWrite 開啟該方法;若不存在,則建立新檔案。 對於現有檔案,它不會將新文字附加到現有文字上。 相反地,它會用新角色覆蓋現有角色。 如果你用較短的字串(例如「Second run」)覆蓋較長的字串(例如「Second run」),檔案中會包含多個字串的混合(「OpenWrite 方法的第二次測試」)。