LoginSignup
6
6

More than 5 years have passed since last update.

テキストファイルを任意の場所から読む方法

Posted at

テキストファイルは始めから一行ずつ読み込んでいくのが普通ですが、以下の方法を使うとテキストファイルの途中から読み始めることが出来ます。詳細は、http://d.hatena.ne.jp/funayoi/20080120/1200837828 を参照してください。

// ファイルストリームを開く
var fs = System.IO.File.OpenRead("file.txt");
// 先ほどのファイルストリームを元に、Shift-JISのテキストを読み込むストリームを作成
var sr = new System.IO.StreamReader(fs, System.Text.Encoding.GetEncoding("Shift_JIS"));

// ファイルの中間の場所にシーク
long pos = fs.Length / 2;
fs.Seek(pos, System.IO.SeekOrigin.Begin);
// シークした位置から一行読み込む
string line = sr.ReadLine();

ちなみに、ファイルの位置はStreamReaderオブジェクトのPositionプロパティで取得できます。

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6