C#にてシーケンシャル読み込み・書き込みの方法を説明します。
シーケンシャルファイルを読み書きするには、幾つかの方法がありますが、StreamReader ・ StreamWriter を使用する方法を記載します。
シーケンシャル読み込み
string inFilePath = @"C:\work\myfile.txt";
List<string> dtList = new List<string>();
try
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(inFilePath, System.Text.Encoding.GetEncoding("Shift_JIS")))
{
while (!sr.EndOfStream)
{
dtList.Add(sr.ReadLine());
}
sr.Close(); //usingの場合Closeは必ずしも必要ではない
}
}
catch (Exception e)
{
}
シーケンシャル書き込み
string outFilePath = @"C:\work\myfile.txt";
List<string> dtList = new List<string>();
データの設定・・・
try
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outFilePath, false, System.Text.Encoding.GetEncoding("Shift_JIS")))
{
foreach (string s in dtList)
{
sw.WriteLine(s);
}
sw.Close(); //usingの場合Closeは必ずしも必要ではない
}
}
catch (Exception e)
{
}