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

書き込み用に開くファイル。

返品

UTF-8 エンコードを使用して指定したファイルに書き込む StreamWriter

例外

呼び出し元に必要なアクセス許可がありません。

-または-

path は、読み取り専用のファイルを指定しました。

-または-

path は、非表示のファイルを指定しました。

2.1 より前のバージョンの .NET Framework と .NET Core: path は長さ 0 の文字列で、空白のみを含むか、1 つ以上の無効な文字を含みます。 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

注釈

このメソッドは、append パラメーターを false に設定したStreamWriter(String, Boolean) コンストラクターのオーバーロードと同じです。 pathで指定されたファイルが存在しない場合は作成されます。 ファイルが存在する場合は、その内容が置き換えられます。 その他のスレッドは、開いている間にファイルを読み取るために許可されます。

path パラメーターは、相対パス情報または絶対パス情報を指定できます。 相対パス情報は、現在の作業ディレクトリに対する相対パスとして解釈されます。 現在の作業ディレクトリを取得するには、 GetCurrentDirectoryを参照してください。

一般的な I/O タスクの一覧については、「 一般的な I/O タスク」を参照してください。

適用対象

こちらもご覧ください