this.治疗完毕

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#读取TXT文本指定行

//原理:直接读第n行对流操作来是不可行的。通常的处理方法是:先读出前面n-1行但不处理,直到读出第n行时再处理。至于去掉头尾的引号,截个子串就行了: 

 class Program
    {
        static void Main(string[] args)
        {
            FileStream fs = null;
            StreamReader r = null;
            string str;
            int row;
 
            try
            {
                fs = new FileStream("data.txt", FileMode.Open);
                r = new StreamReader(fs);
 
                do
                {
                    Console.WriteLine("请输入要查询的行数(>0):");
                    str = Console.ReadLine();
 
                    if (!(int.TryParse(str, out row)))
                        Console.WriteLine("请输入整数!");
                } while (row < 1);
 
                for (int i = 0; i < row - 1 && !r.EndOfStream; r.ReadLine(), i++) ;
 
                str = r.ReadLine();
 
                Console.WriteLine("查到的行:");
 
                Console.WriteLine(str.Substring(str.IndexOf('"') + 1, str.LastIndexOf('"') - str.IndexOf('"') - 1));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (r != null)
                    r.Close();
 
                if (fs != null)
                    fs.Close();
            }
        }
    }
 

 

posted on 2018-05-31 14:45  this.治疗完毕  阅读(1472)  评论(0)    收藏  举报