Seek Method无法读取文本文件C#

时间:2013-04-26 01:56:10

标签: c# methods filestream streamreader seek

使用Seek Method读取文本的特定部分,但失败了。

我有两个类“allmethods.cs”和“caller.cs”

“allmethods.cs”中有两种方法,分别是“WritingMethod”和“SeekReader”

程序应该在文本文件中写入并使用搜索方法读取数据,以便读取文本文件中的某些部分。

程序在文本文件中顺利写入,但在调用“SeekReader”时,它不会读取任何内容。

我的代码:

 public class allmethods
{
    private static string Name;
    private static int ID;
    private static int Age;
    private static string Email;
    private static string output;

    public static void WritingMethod()
        {
             int count = 0;
             while (count < 10)      
            {
            Console.Write(" Enter your Name: ");
            Name = Console.ReadLine();

            Console.Write(" Enter your ID: ");
            ID = int.Parse(Console.ReadLine());

            Console.Write(" Enter your Age: ");
            Age = int.Parse(Console.ReadLine());

            Console.Write(" Enter your E-mail: ");
            Email = Console.ReadLine();

        StreamWriter Sw = new StreamWriter("fileone.txt", true);
        string output = string.Format("Thank you for registration! Your Submitted information are:" + Environment.NewLine + "Name: {0}"
        + Environment.NewLine + "ID: {1}" + Environment.NewLine + "Age: {2}" + Environment.NewLine + "E-mail: {3}", Name, ID, Age, Email);
        Console.WriteLine(output);      
        Sw.WriteLine(output + Environment.NewLine);
        Console.ReadLine();

        Sw.Close();
        count++;
        }

    }

 public static void SeekReader()
     {
         FileStream FS=new FileStream("fileone.txt",FileMode.Open,FileAccess.Read);
         StreamReader SR = new StreamReader(FS);
         SR.BaseStream.Seek(2, SeekOrigin.Begin);

         FS.Close();
         SR.Close();
     }
}

我未能确定错误。有什么建议吗?

先谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用File.ReadAllText([FilePah])来阅读该文件。

public static void SeekReader()     {

    FileStream fsr = new FileStream("fileone.txt", FileMode.Open, FileAccess.Read);     
    StreamReader Sr = new StreamReader(fsr);      
    string line = string.Empty;
    var ctr = 0;
    while(ctr < 3){
      line = Sr.ReadLine();
      ctr++;
    }
    Console.WriteLine(line);

    Sr.Close();
    fsr.Close();
}