查找方法读取文本文件失败

本文关键字:文件 失败 取文本 读取 方法 查找 | 更新日期: 2023-09-27 18:10:52

使用Seek方法读取文本的特定部分但失败

我有两个类"allmethods.cs"answers"caller.cs"

在"allmethods.cs"中有两个方法分别是"WritingMethod"answers"SeekReader"

程序应该在文本文件中写入数据,并使用seek方法读取数据,以便读取文本文件中的特定部分。

程序在文本文件中平滑地写入,但在调用"SeekReader"(即seek方法)时不读取任何内容。

我代码:

 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();
     }
}

我未能识别错误。有什么建议吗?

查找方法读取文本文件失败

可以使用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();
}