どっとねっとふぁん

C# Tips And Samples
in 検索

15.ファイルの利用入出力

最新の投稿は、投稿日時: 06-22-2005, 4:17 午後 投稿者: ono です。スレッドには 0 件の返答があります。
投稿のソート: 前へ 次へ
  •  06-22-2005, 4:17 午後 24

    15.ファイルの利用入出力

    ファイルとデータをやりとりする場合の基本形です。
    日本語の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();
            }
        }
    
    }
    
    -------------------------------------------------------
    ファイルをきちんと閉じないと、データが最後まで書かれない場合があります。
    開けたら閉じる、が基本ですね。



    あおい情報システム株式会社
     小野修司(どっとねっとふぁん)
RSS ニュースフィードで参照
SkinName:iroha_CS2
Powered by Community Server, by Telligent Systems