英語で読む

次の方法で共有


FileInfo.AppendText メソッド

定義

FileInfoのインスタンスが表すファイルの末尾にテキストを追加するStreamWriterを作成します。

public System.IO.StreamWriter AppendText ();

戻り値

新しい StreamWriter

次の例では、ファイルにテキストを追加し、ファイルから読み取ります。

using System;
using System.IO;

class Test
{
    
    public static void Main()
    {
        FileInfo fi = new FileInfo(@"c:\MyTest.txt");

        // This text is added only once to the file.
        if (!fi.Exists)
        {
            //Create a file to write to.
            using (StreamWriter sw = fi.CreateText())
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }	
        }

        // This text will always be added, making the file longer over time
        // if it is not deleted.
        using (StreamWriter sw = fi.AppendText())
        {
            sw.WriteLine("This");
            sw.WriteLine("is Extra");
            sw.WriteLine("Text");
        }	

        //Open the file to read from.
        using (StreamReader sr = fi.OpenText())
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//Hello
//And
//Welcome
//This
//is Extra
//Text

//When you run this application a second time, you will see the following output:
//
//Hello
//And
//Welcome
//This
//is Extra
//Text
//This
//is Extra
//Text

次の例では、ファイルの末尾にテキストを追加し、追加操作の結果をコンソールに表示する方法を示します。 このルーチンを初めて呼び出すと、ファイルが存在しない場合は作成されます。 その後、指定したテキストがファイルに追加されます。

using System;
using System.IO;

public class AppendTextTest
{
    public static void Main()
    {
        FileInfo fi = new FileInfo("temp.txt");
        // Create a writer, ready to add entries to the file.
        StreamWriter sw = fi.AppendText();
        sw.WriteLine("Add as many lines as you like...");
        sw.WriteLine("Add another line to the output...");
        sw.Flush();
        sw.Close();
        // Get the information out of the file and display it.
        // Remember that the file might have other lines if it already existed.
        StreamReader sr = new StreamReader(fi.OpenRead());
        while (sr.Peek() != -1)
            Console.WriteLine( sr.ReadLine() );
    }
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//Add as many lines as you like...
//Add another line to the output...

適用対象

こちらもご覧ください