File.CreateText(String) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
建立或開啟一個用於撰寫 UTF-8 編碼文字的檔案。 如果檔案已經存在,其內容會被替換。
public:
static System::IO::StreamWriter ^ CreateText(System::String ^ path);
public static System.IO.StreamWriter CreateText(string path);
static member CreateText : string -> System.IO.StreamWriter
Public Shared Function CreateText (path As String) As StreamWriter
參數
- path
- String
檔案將被開啟以供撰寫。
傳回
StreamWriter A 會使用 UTF-8 編碼寫入指定的檔案。
例外狀況
.NET Framework 與 .NET Core 版本 2.1 以前: path 為零長度字串、僅含空白,或包含一個或多個無效字元。 你可以用這個 GetInvalidPathChars() 方法查詢無效字元。
path 是 null。
指定的路徑、檔名或兩者都超過系統定義的最大長度。
指定的路徑無效(例如,它位於未對應的磁碟驅動器上)。
path 格式無效。
範例
以下範例建立一個用於文字寫入與讀取的檔案。
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
open System.IO
let path = @"c:\temp\MyTest.txt"
if File.Exists path |> not then
// Create a file to write to.
use sw = File.CreateText path
sw.WriteLine "Hello"
sw.WriteLine "Welcome"
// Open the file to read from.
do
use sr = File.OpenText path
let mutable s = sr.ReadLine()
while isNull s |> not do
printfn $"{s}"
s <- sr.ReadLine()
Imports System.IO
Imports System.Text
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
If Not File.Exists(path) Then
' Create a file to write to.
Using sw As StreamWriter = File.CreateText(path)
sw.WriteLine("Hello")
sw.WriteLine("And")
sw.WriteLine("Welcome")
End Using
End If
' Open the file to read from.
Using sr As StreamReader = File.OpenText(path)
Do While sr.Peek() >= 0
Console.WriteLine(sr.ReadLine())
Loop
End Using
End Sub
End Class
備註
此方法等同 StreamWriter(String, Boolean) 於參數 append 設為 false的建構子過載。 如果指定的檔案不存在,則會建立該檔案 path 。 如果檔案存在,其內容會被替換。 在檔案開啟時,允許額外的執行緒讀取。
path參數允許指定相對或絕對路徑資訊。 相對路徑資訊會被解讀為相對於目前工作目錄的相對於。 欲取得目前的工作目錄,請參見 GetCurrentDirectory。
關於常見 I/O 任務的清單,請參見 Common I/O 任務。