File.CreateText(String) 方法

定义

创建或打开用于编写 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使用 UTF-8 编码写入指定文件。

例外

调用方没有所需的权限。

-或-

path 指定为只读的文件。

-或-

path 指定隐藏的文件。

低于 2.1 的 .NET Framework 和 .NET Core 版本: path 是长度为零的字符串,仅包含空格,或包含一个或多个无效字符。 可以使用该方法 GetInvalidPathChars() 查询无效字符。

pathnull

指定的路径、文件名或两者都超过了系统定义的最大长度。

指定的路径无效(例如,它位于未映射的驱动器上)。

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)将参数设置为appendfalse构造函数重载。 如果文件 path 不存在,则会创建该文件。 如果文件存在,则会替换其内容。 允许在文件打开时读取其他线程。

允许参数 path 指定相对路径或绝对路径信息。 相对路径信息解释为相对于当前工作目录。 若要获取当前工作目录,请参阅 GetCurrentDirectory

有关常见 I/O 任务的列表,请参阅 常见 I/O 任务

适用于

另请参阅