ファイルとデータをやりとりする場合の基本形です。
日本語のWindows環境では、テキストファイルは普通Shift-JIS形式になっています。
そのため、エンコーディングを明示的に指定する必要があります。
ファイルからデータを読み込んでコンソール上に表示します。
-------------------------------------------------------
using System;
using System.IO;
public class Sample {
public static void Main(string[] args) {
string str = null;
// ファイルの存在チェックをして、存在していれば読み込む
if(File.Exists(args[0]))
{
StreamReader sR = new StreamReader(args[0], System.Text.Encoding.GetEncoding("Shift-JIS"));
while((str=sR.ReadLine())!=null)
Console.WriteLine(str);
sR.Close();
}
}
}
-------------------------------------------------------
コンソール上から入力した文字を指定したファイルに書き出します。
入力を終了するにはCtrl+Zを入力します。
-------------------------------------------------------
using System;
using System.IO;
public class Sample {
public static void Main(string[] args) {
if(args.Length == 1)
{
string str = null;
StreamWriter sW = new StreamWriter(args[0], false, System.Text.Encoding.GetEncoding("Shift-JIS"));
while((str=Console.ReadLine()) != null){
sW.WriteLine(str);
}
sW.Close();
}
}
}
-------------------------------------------------------
ファイルをきちんと閉じないと、データが最後まで書かれない場合があります。
開けたら閉じる、が基本ですね。
あおい情報システム株式会社 小野修司(どっとねっとふぁん)