C# でのファイルの読み取りと書き込み
-
C# の
File.WriteAllText()メソッドを使用してファイルにデータを書き込む -
C# の
File.ReadAllText()メソッドを使用してファイルからデータを読み取る -
C# の
StreamWriterクラスを使用してファイルにデータを書き込む -
C# の
StreamReaderクラスを使用してファイルからデータを読み取る
このチュートリアルでは、C# でファイルの読み取りと書き込みを行う方法について説明します。
C# の File.WriteAllText() メソッドを使用してファイルにデータを書き込む
File クラスは、C# でファイルを処理するための機能を提供します。File.WriteAllText(path) メソッドを使用して、パス path 内のファイルに文字列を書き込むことができます。次のコード例は、C# で File.WriteAllText() 関数を使用してファイルにデータを書き込む方法を示しています。
using System;
using System.IO;
namespace write_to_a_file {
class Program {
static void Main(string[] args) {
string path = "C:\\File\\file.txt";
string Text = "Hello, Hi, ByeBye";
File.WriteAllText(path, Text);
}
}
}
file.txt の内容:
Hello, Hi, ByeBye
上記のコードでは、パス C:\File 内にテキストファイル file.txt を作成し、C# の File.WriteAllText(path, Text) 関数を用いて文字列変数 Text を file.txt ファイルに書き込んでいます。
C# の File.ReadAllText() メソッドを使用してファイルからデータを読み取る
File.ReadAllText() メソッドを使用して、文字列変数の形式でファイルからデータを読み取ることができます。File.ReadAllText() メソッドは、ファイルのパスをパラメーターとして受け取り、ファイルの内容を文字列データ型で返します。次のコード例は、C# の File.ReadAllText() メソッドを使用してファイルからデータを読み取る方法を示しています。
using System;
using System.IO;
namespace write_to_a_file {
class Program {
static void Main(string[] args) {
string path = "C:\\File\\file.txt";
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
}
}
出力:
Hello, Hi, ByeBye
上記のコードでは、以前に C:\File ディレクトリ内の file.txt ファイルに書き込まれたすべてのデータを File.ReadAllText(path) メソッドで読み取り、ユーザーに表示しました。
C# の StreamWriter クラスを使用してファイルにデータを書き込む
StreamWriter クラスは、C# の特定のエンコーディングでストリームにデータを書き込むために使用されます。StreamWrite.WriteLine() メソッドを使用して、文字列変数をファイルに書き込むことができます。次のコード例は、C# で StreamWriter.WriteLine() メソッドを使用してファイルにデータを書き込む方法を示しています。
using System;
using System.IO;
namespace write_to_a_file {
class Program {
static void Main(string[] args) {
string path = "C:\\File\\file.txt";
string Text = "Hello and Welcome";
using (StreamWriter writetext = new StreamWriter(path)) {
writetext.WriteLine(Text);
}
}
}
}
file.txt の内容:
Hello and Welcome
上記のコードでは、StreamWriter クラスのオブジェクトを作成し、文字列変数 Text を writetext.WriteLine(Text) を使用して C:\File ディレクトリ内の file.txt ファイルに書き込みました。C# で機能します。
C# の StreamReader クラスを使用してファイルからデータを読み取る
StreamReader クラスは、C# の特定のエンコーディングでストリームからデータを読み取るために使用されます。StreamReader.ReadLine() メソッドを使用して、ファイルから文字列データを読み取ることができます。次のコード例は、C# で StreamReader.ReadLine() メソッドを使用してファイルからデータを読み取る方法を示しています。
using System;
using System.IO;
namespace write_to_a_file {
class Program {
static void Main(string[] args) {
string path = "C:\\File\\file.txt";
using (StreamReader readtext = new StreamReader(path)) {
string readText = readtext.ReadLine();
Console.WriteLine(readText);
}
}
}
}
出力:
Hello and Welcome
上記のコードでは、StreamReader クラスのオブジェクトを作成し、readtext.ReadLine() 関数を使用して C:\File ディレクトリ内の file.txt ファイルに以前に書き込まれたすべてのデータを読み取りました。ユーザーに表示しました。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn