Earn More by Sharing What You Love
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!

Tim Corey
24分34秒
C#のファイル入出力(I/O)操作は、多くのソフトウェアアプリケーションに不可欠な要素であり、開発者はファイルからの読み取りとファイルへの書き込みを効率的に行うことができます。 データの保存、アプリケーションイベントのログ、大量のテキストデータやバイナリデータの処理など、C#はファイルを扱うための堅牢なツールを提供します。 ティム・コーリーのビデオ"C# Data Access:テキストファイル"では、データの保存と検索の両方にテキストファイルを使用する方法に焦点を当て、これらのファイル操作の詳細なウォークスルーを提供しています。 この記事では、ティムがビデオで取り上げた主要な概念とテクニックを要約し、C#でのファイルI/O操作に関する実践的な洞察を提供することを目的としています。
C#では、ファイルの入出力操作は、テキストファイルからの読み取りとテキストファイルへの書き込みに不可欠です。 Fileクラスは、既存のファイルと対話したり、新しいファイルを作成したりするための静的メソッドを提供します。 StreamWriterは、ファイルの読み書きに一般的に使用されます。 StreamReaderはファイルを行単位で読み込むことで、各行のテキストや文字列の配列にアクセスできます。 また、whileループを使用して、大きなファイルを効率的に読むこともできます。 StreamWriterクラスは、文字列や配列の書き出しをサポートし、データをファイルに書き込むために使用されます。 テキストを既存のファイルに追加したり、ファイル全体を上書きしたりすることができます。WriteTextのようなメソッドにより、テキストファイル内でのデータ操作が簡単になります。
これらの操作は通常、ファイルパスを定義するstatic void Mainメソッド内で実行されます。 例えば、ファイル名を指定し、StreamWriterを使用して単一の文字列または文字列の配列全体を書き込むことができます。 usingステートメントは、操作が完了した後にファイルが適切に閉じられることを保証し、リソースリークを防ぎます。 StreamReaderは、行単位でファイルを読み込むためにも使用でき、ファイルが存在しないかアクセスできない場合の潜在的なエラーを管理するために例外を処理することができます。 これらのファイルI/O機能により、C#はファイルを効率的かつ効果的に扱うための優れた選択肢となっています。
Timは、C#でテキストファイルから読み込んだり、テキストファイルに書き込んだりすることの簡単さを強調することで、このトピックを紹介します。 数行のコードでこれらのタスクを実現し、テキスト・ファイルをデータ・ストレージの有力な選択肢にする方法を示す。
Timはまず、Visual Studioを使って "TextFileDataAccessDemo "という名前の新しいコンソールアプリケーションを作成します。
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace TextFileDataAccessDemo
{
class Program
{
static void Main(string[] args)
{
Console.ReadLine(); // Keeps the console window open to view the output
}
}
}Imports System
Imports System.IO
Imports System.Collections.Generic
Imports System.Linq
Namespace TextFileDataAccessDemo
Class Program
Shared Sub Main(ByVal args As String())
Console.ReadLine() ' Keeps the console window open to view the output
End Sub
End Class
End NamespaceImports System
Imports System.IO
Imports System.Collections.Generic
Imports System.Linq
Namespace TextFileDataAccessDemo
Class Program
Shared Sub Main(ByVal args As String())
Console.ReadLine() ' Keeps the console window open to view the output
End Sub
End Class
End Namespace彼は、Console.ReadLineの使用法を説明し、コンソールウィンドウを開いたままにすることで、ユーザーが出力を確認できるようにします。
Timは、File.ReadAllLinesメソッドを使ってテキストファイルを読み込む方法を示します。 ファイルパスの扱い方や、エスケープ文字を避けるための文字列リテラルの使い方も紹介しています。
string filePath = @"C:\demos\test.txt";
List<string> lines = File.ReadAllLines(filePath).ToList();string filePath = @"C:\demos\test.txt";
List<string> lines = File.ReadAllLines(filePath).ToList();Dim filePath As String = "C:\demos\test.txt"
Dim lines As List(Of String) = File.ReadAllLines(filePath).ToList()Dim filePath As String = "C:\demos\test.txt"
Dim lines As List(Of String) = File.ReadAllLines(filePath).ToList()File.ReadAllLinesメソッドは、指定されたファイルからすべての行を読み込み、文字列の配列として返します。 Timは、この配列をリストに変換して、簡単に操作できるようにします。
Timは、File.WriteAllLinesメソッドを使ってデータをテキストファイルに書き込む方法を説明します。 彼は、リストに新しい行を追加し、更新されたリストをファイルに書き戻す方法を示します。
lines.Add("Sue,Storm,WWIStorm.com");
File.WriteAllLines(filePath, lines);lines.Add("Sue,Storm,WWIStorm.com");
File.WriteAllLines(filePath, lines);lines.Add("Sue,Storm,WWIStorm.com")
File.WriteAllLines(filePath, lines)lines.Add("Sue,Storm,WWIStorm.com")
File.WriteAllLines(filePath, lines)このコードは、リストに新しいエントリーを追加し、リスト全体をファイルに書き戻します。
Timは、テキストファイルの各エントリーのデータ構造を表すPersonクラスを作成します。
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string URL { get; set; }
}public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string URL { get; set; }
}Public Class Person
Public Property FirstName As String
Public Property LastName As String
Public Property URL As String
End ClassPublic Class Person
Public Property FirstName As String
Public Property LastName As String
Public Property URL As String
End Classその後、彼はファイルを読み込み、Personオブジェクトのリストを作成します。
List<Person> people = new List<Person>();
List<string> lines = File.ReadAllLines(filePath).ToList();
foreach (string line in lines)
{
string[] entries = line.Split(',');
Person newPerson = new Person
{
FirstName = entries[0],
LastName = entries[1],
URL = entries[2]
};
people.Add(newPerson);
}List<Person> people = new List<Person>();
List<string> lines = File.ReadAllLines(filePath).ToList();
foreach (string line in lines)
{
string[] entries = line.Split(',');
Person newPerson = new Person
{
FirstName = entries[0],
LastName = entries[1],
URL = entries[2]
};
people.Add(newPerson);
}Dim people As New List(Of Person)()
Dim lines As List(Of String) = File.ReadAllLines(filePath).ToList()
For Each line As String In lines
Dim entries As String() = line.Split(","c)
Dim newPerson As New Person With {
.FirstName = entries(0),
.LastName = entries(1),
.URL = entries(2)
}
people.Add(newPerson)
NextDim people As New List(Of Person)()
Dim lines As List(Of String) = File.ReadAllLines(filePath).ToList()
For Each line As String In lines
Dim entries As String() = line.Split(","c)
Dim newPerson As New Person With {
.FirstName = entries(0),
.LastName = entries(1),
.URL = entries(2)
}
people.Add(newPerson)
Nextこのコードは各行を読み込み、カンマで分割して、抽出したデータでPersonオブジェクトを作成します。
ティムは、変数と文字列を組み合わせるプロセスを簡素化するC# 6.0の機能である文字列補間を紹介します。 このメソッドは、文字列の前に{}を使用して、変数を直接文字列内に埋め込みます。
foreach (var person in people)
{
Console.WriteLine($"{person.FirstName} {person.LastName}: {person.URL}");
}foreach (var person in people)
{
Console.WriteLine($"{person.FirstName} {person.LastName}: {person.URL}");
}For Each person In people
Console.WriteLine($"{person.FirstName} {person.LastName}: {person.URL}")
NextFor Each person In people
Console.WriteLine($"{person.FirstName} {person.LastName}: {person.URL}")
Nextこの構文は、+演算子を使った従来の連結よりも簡潔で効率的です。

ティムは、テキストファイルからデータを読み込む際の検証の重要性を強調する。彼は、データの構造を仮定することのリスクを指摘し、分割されたエントリの長さをチェックすることを推奨しています。
foreach (string line in lines)
{
string[] entries = line.Split(',');
if (entries.Length == 3)
{
Person newPerson = new Person
{
FirstName = entries[0],
LastName = entries[1],
URL = entries[2]
};
people.Add(newPerson);
}
else
{
// Handle error
Console.WriteLine("Invalid data format.");
}
}foreach (string line in lines)
{
string[] entries = line.Split(',');
if (entries.Length == 3)
{
Person newPerson = new Person
{
FirstName = entries[0],
LastName = entries[1],
URL = entries[2]
};
people.Add(newPerson);
}
else
{
// Handle error
Console.WriteLine("Invalid data format.");
}
}For Each line As String In lines
Dim entries As String() = line.Split(","c)
If entries.Length = 3 Then
Dim newPerson As New Person With {
.FirstName = entries(0),
.LastName = entries(1),
.URL = entries(2)
}
people.Add(newPerson)
Else
' Handle error
Console.WriteLine("Invalid data format.")
End If
NextFor Each line As String In lines
Dim entries As String() = line.Split(","c)
If entries.Length = 3 Then
Dim newPerson As New Person With {
.FirstName = entries(0),
.LastName = entries(1),
.URL = entries(2)
}
people.Add(newPerson)
Else
' Handle error
Console.WriteLine("Invalid data format.")
End If
Nextこれにより、正確なエントリ数の行のみが処理され、潜在的なランタイムエラーが回避されます。
Timはリストに新しいオブジェクトを追加する方法を示します。彼はPersonクラスの無名インスタンスを使用して、リストに新しい人物を追加します。
people.Add(new Person { FirstName = "Greg", LastName = "Jones", URL = "WOWT.com" });people.Add(new Person { FirstName = "Greg", LastName = "Jones", URL = "WOWT.com" });people.Add(New Person With {.FirstName = "Greg", .LastName = "Jones", .URL = "WOWT.com"})people.Add(New Person With {.FirstName = "Greg", .LastName = "Jones", .URL = "WOWT.com"})これは、単一の行で新しいpeopleリストに追加します。
TimはPersonオブジェクトのリストを文字列のリストに変換し、各文字列がファイル内の行を表します。
List<string> output = new List<string>();
foreach (var person in people)
{
output.Add($"{person.FirstName},{person.LastName},{person.URL}");
}
File.WriteAllLines(filePath, output);List<string> output = new List<string>();
foreach (var person in people)
{
output.Add($"{person.FirstName},{person.LastName},{person.URL}");
}
File.WriteAllLines(filePath, output);Dim output As New List(Of String)()
For Each person In people
output.Add($"{person.FirstName},{person.LastName},{person.URL}")
Next
File.WriteAllLines(filePath, output)Dim output As New List(Of String)()
For Each person In people
output.Add($"{person.FirstName},{person.LastName},{person.URL}")
Next
File.WriteAllLines(filePath, output)このコードはPersonオブジェクトのCSV文字列を作成し、文字列のリストをファイルに書き込みます。
Tim CoreyによるC#でのファイルI/O操作に関する詳細なガイドは、テキストファイルからの読み取りとテキストファイルへの書き込みに関する実践的な洞察を提供します。 彼の例に従うことで、開発者はテキストファイルを使って効果的にデータを管理し、堅牢なデータストレージソリューションを実装することができます。 より深い理解と実践的な学習体験のために、ティム・コーリーのビデオをぜひご覧ください。実例を挙げながら、これらの概念を深く掘り下げています。
Do you create content for developers working with .NET, C#, Java, Python, or Node.js? Turn your expertise into extra income!

Join our newsletter, you’ll get exclusive access on article updates. We value your privacy