سؤال

تكرار ممكن:
ج # قراءة ملف سطرا بسطر
كيفية حلقة على خطوط من تكستريدر?

أنا أعطيت صافي تكستريدر (فئة يمكنها قراءة سلسلة متسلسلة من الأحرف).كيف يمكنني تكرار محتواه حسب السطر?

هل كانت مفيدة؟

المحلول

هل تقصد شيئا كهذا?

string line = null;
while((line = reader.ReadLine()) != null) 
{
    // do something with line
}

نصائح أخرى

يمكنك إنشاء طريقة تمديد بسهولة جدا بحيث يمكنك استخدامها foreach:

public static IEnumerable<string> ReadLines(this TextReader reader)
{
    string line = null;
    while((line = reader.ReadLine()) != null) 
    {
        yield return line;
    }
}

لاحظ أن هذا لن أغلق القارئ لك في النهاية.

يمكنك بعد ذلك استخدام:

foreach (string line in reader.ReadLines())

تحرير:كما لوحظ في التعليقات ، هذا كسول.وسوف تقرأ فقط خط في وقت واحد ، بدلا من قراءة جميع الخطوط في الذاكرة.

الحل غير الكسول لدي في الوقت الحالي:

foreach(string line in source.ReadToEnd().Split(Environment.NewLine.ToArray(),StringSplitOptions.None))

يمكنك استخدامه مثل هذا:

string line;
while ((line = myTextReader.ReadLine()) != null)
{
    //do whatever with "line";
}

أو

string Myfile = @"C:\MyDocument.txt";
using(FileStream fs = new FileStream(Myfile, FileMode.Open, FileAccess.Read))
{                    
    using(StreamReader sr = new StreamReader(fs))
    {
        while(!sr.EndOfStream)
        {
            Console.WriteLine(sr.ReadLine());
        }
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top