Question

Using Seek Method to read a specific part of a text but it fails.

I have two classes "allmethods.cs" and "caller.cs"

There are two methods in "allmethods.cs" which are "WritingMethod" and "SeekReader"

The program should writes in a text file and read data using seek method in order to read certain part in the text file.

The programs writes smoothly in the text file but it doesn't read anything when calling "SeekReader" which is the seek method.

My Code:

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

I failed to identify the error. Any suggestions?

Thanks in Advance.

Was it helpful?

Solution

You can use File.ReadAllText([FilePah]) to read the file.

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top