サンプル集  >  C#  >  ファイルの内容表示
ファイルの内容表示
2015/12/25

ファイルを読み込み内容を表示します。

◆環境
OS Windows 7 Professional Service Pack 1 64bit
C# Microsoft Visual C# 2010 01018-587-4111284-70817

[ファイル]-[新規作成]-[プロジェクト]を選択。

[コンソール アプリケーション]を選択し、名前に「MyCat」と入力し「OK」。

ファイルの操作にはStremReaderを利用します。

Program.cs
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MyCat
{
    class Program
    {
        static void Main( string[] args )
        {
            // 引数で受け取ったファイル名のファイルを開く
            Console.WriteLine( "File name:" + args[0] );
            StreamReader sr
            = new StreamReader(
                args[0]
              , Encoding.GetEncoding( "Shift_JIS" )
            );

            // ファイルの内容を1行ずつ読み込み表示
            string line = "";
            for ( int i = 0; ; i++ )
            {
                line = sr.ReadLine();
                if ( line == null )
                {
                    break;
                }
                Console.WriteLine( ( i + 1 ) + ":\t" + line );
            }

            // ファイルを閉じる
            sr.Close();
        }
    }
}

今回作成したプログラムを表示してみます。

> MyCat.exe ..\src\Program.cs
File name:..\src\Program.cs
1:      using System;
2:      using System.Collections.Generic;
3:      using System.Linq;
:

:
35:             }
36:         }
37:     }

ファイルの内容が表示されました。

▲ PageTop  ■ Home


Copyright (C) 2015 ymlib.com