2013-04-26 53 views
0

使用Seek Method讀取文本的特定部分,但失敗。Seek Method無法讀取文本文件C#

我有兩個班「allmethods.cs」和「caller.cs」

有兩種方法在「allmethods.cs」,這是「WritingMethod」和「SeekReader」

程序應該寫入在文本文件中使用seek方法讀取數據以讀取文本文件中的某個部分。

程序在文本文件中順利寫入,但在調用作爲查找方法的「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(); 
    } 
} 

我沒有找出錯誤。有什麼建議麼?

在此先感謝。

+0

似乎類似於http://stackoverflow.com/questions/16227263/streamreader-doesnt-read-data-in-text-file-c-sharp/16227286?noredirect = 1#comment23211047_16227286 – ysrb 2013-04-26 01:57:43

回答

1

您可以使用File.ReadAllText([FilePah])來讀取文件。

公共靜態無效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(); 
} 
+0

是的,但我想讀取文本文件的某個部分。感謝您的回覆。 – 2013-04-26 02:01:17

+0

你想讀取哪個文件的哪一部分? – ysrb 2013-04-26 02:04:29

+0

只想閱讀第3行.. – 2013-04-26 02:23:30