「C#」CreateTextでファイルにテキストを書き込む

書式
1.public System.IO.StreamWriter CreateText ();
新しいテキストファイルに書き込みを実行する StreamWriter を作成します。
戻り値 新しい StreamWriter。
2.public System.IO.StreamReader OpenText ();
既存のテキスト ファイルからの読み取りを行う、UTF8 エンコーディングの StreamReader を作成します。
戻り値 UTF8 エンコーディングの新しい StreamReader。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using System;
using System.IO;
namespace ConsoleApplicationSample
{
class Program
{
static void Main(string[] args)
{
string path = @"C:\study\charp\test007.txt";
FileInfo fi = new FileInfo(path);
//ファイルが存在しない場合
if (!fi.Exists)
{
//ファイル作成 新しい StreamWriter
using (StreamWriter sw = fi.CreateText())
{ //ファイルにテキストを書き込む
sw.WriteLine("Study");
sw.WriteLine("Skill");
sw.WriteLine("Become");
sw.WriteLine("Smart");
}
}
//ファイルを開いて内容を読む ファイルからの読み取りを行う
using (StreamReader sr = fi.OpenText())
{
string res = "";
//ファイルの内容を読む
while ((res = sr.ReadLine()) != null)
{
Console.WriteLine(res);
}
}
Console.ReadKey();
}
}
}
using System; using System.IO; namespace ConsoleApplicationSample { class Program { static void Main(string[] args) { string path = @"C:\study\charp\test007.txt"; FileInfo fi = new FileInfo(path); //ファイルが存在しない場合 if (!fi.Exists) { //ファイル作成 新しい StreamWriter using (StreamWriter sw = fi.CreateText()) { //ファイルにテキストを書き込む sw.WriteLine("Study"); sw.WriteLine("Skill"); sw.WriteLine("Become"); sw.WriteLine("Smart"); } } //ファイルを開いて内容を読む ファイルからの読み取りを行う using (StreamReader sr = fi.OpenText()) { string res = ""; //ファイルの内容を読む while ((res = sr.ReadLine()) != null) { Console.WriteLine(res); } } Console.ReadKey(); } } }
using System;
using System.IO;

namespace ConsoleApplicationSample
{
    class Program
    {
        static void Main(string[] args)
        {

            string path = @"C:\study\charp\test007.txt";
            FileInfo fi = new FileInfo(path);

            //ファイルが存在しない場合
            if (!fi.Exists)
            {
                //ファイル作成 新しい StreamWriter
                using (StreamWriter sw = fi.CreateText())
                {   //ファイルにテキストを書き込む
                    sw.WriteLine("Study");
                    sw.WriteLine("Skill");
                    sw.WriteLine("Become");
                    sw.WriteLine("Smart");
                }
            }

            //ファイルを開いて内容を読む ファイルからの読み取りを行う
            using (StreamReader sr = fi.OpenText())
            {
                string res = "";
                //ファイルの内容を読む
                while ((res = sr.ReadLine()) != null)
                {
                    Console.WriteLine(res);
                }
            }
            Console.ReadKey();
        }
    }
}

実行結果
1.「C:\study\charp\test007.txt」ファイルに以下の内容を書き込みました
Study
Skill
Become
Smart

2.コンソールに以下の内容が表示されます。
Study
Skill
Become
Smart

C#

Posted by arkgame