【问题标题】:Seek Method fails to read the text file C#Seek 方法无法读取文本文件 C#
【发布时间】:2013-04-26 01:56:10
【问题描述】:

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

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

“allmethods.cs”中有两个方法,“WritingMethod”和“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();
     }
}

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

提前致谢。

【问题讨论】:

标签: c# methods filestream streamreader seek


【解决方案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();
}

【讨论】:

  • 是的,但我想阅读文本文件的某个部分。感谢您的回复。
猜你喜欢
  • 2020-07-24
  • 2013-04-01
  • 2011-09-17
  • 1970-01-01
  • 1970-01-01
  • 2017-02-22
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
相关资源
最近更新 更多