← Back to C# Course | Chapter 14: File I/O & Streams | Lesson 2 of 6

StreamReader और StreamWriter

StreamReader और StreamWriter text को एक समय में एक टुकड़ा पढ़ते और लिखते हैं, जैसे किसी किताब को page by page पढ़ना या diary को line by line लिखना। ये बड़ी files के लिए उपयुक्त हैं जिन्हें एक साथ load नहीं करना चाहिए।
Syntax
csharp
using (StreamWriter writer = new StreamWriter(path))
{
    writer.WriteLine("text");
}

using (StreamReader reader = new StreamReader(path))
{
    string line = reader.ReadLine();
}

StreamReader and StreamWriter

StreamReader और StreamWriter text को एक साथ के बजाय धीरे-धीरे पढ़ते और लिखते हैं, जो बड़ी files के लिए ज़्यादा memory-efficient है।

StreamReader.ReadLine() end-of-file पर null return होने तक एक समय में एक line पढ़ता है। दोनों IDisposable implement करते हैं, इसलिए इन्हें एक using block में wrap करना चाहिए।

Note: किसी बड़ी file को एक समय में एक line process करने के लिए while loop में StreamReader.ReadLine() उपयोग करें।

उदाहरण: StreamReader and StreamWriter

markup
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string path = "lines.txt";

        using (StreamWriter writer = new StreamWriter(path))
        {
            writer.WriteLine("line one");
            writer.WriteLine("line two");
        }

        using (StreamReader reader = new StreamReader(path))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
        }
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी StreamWriter को using block में wrap न करना या Dispose call न करना, जिससे buffered text कभी file में flush न हो और file locked रहे।
  2. किसी मौजूदा file के लिए new StreamWriter(path) बनाना और इसकी पुरानी contents खो देना, क्योंकि यह default रूप से overwrite करता है; इसमें जोड़ने के लिए append: true पास करें।
  3. अंत जांचे बिना ReadLine() call करना, जबकि यह आखिरी line के बाद null return करता है; null या reader.EndOfStream तक loop करें।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.