Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3976496
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T04:48:42+00:00 2026-05-20T04:48:42+00:00

I’ve a piece of code: using (StreamReader stream = new StreamReader(file.OpenRead(), Encoding)) { char[]

  • 0

I’ve a piece of code:

using (StreamReader stream = new StreamReader(file.OpenRead(), Encoding))
{
    char[] buffer = new char[chunksize];
    while (stream.Peek() >= 0)
    {
       int readCount = stream.Read(buffer, 0, chunksize);

       yield return new string(buffer, 0, readCount);
    }
 }

Now I have to surround this with an try-catch block

try
{
   using (StreamReader stream = new StreamReader(file.OpenRead(), Encoding))
   {
       char[] buffer = new char[chunksize];
       while (stream.Peek() >= 0)
       {
          int readCount = stream.Read(buffer, 0, chunksize);

          yield return new string(buffer, 0, readCount);
       }
    } 
}
catch (Exception ex)
{
    throw ExceptionMapper.Map(ex, file.FullName)
}

I can’t see any way to do what I want.

The method has the signature:

public IEnumerable<string> ReadPieces(int pieces)

I need a try/catch with a call to the ExceptionMapper in the catch case.
The method is used deferred by all callers.

The exceptions I have to catch are coming from these calls:

File.OpenRead()
stream.Read()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T04:48:42+00:00Added an answer on May 20, 2026 at 4:48 am

    Because you want to keep the Stream open for the duration of the enumeration AND deal with exceptions AND properly close the file handle either way, I don’t think you can use a regular enumeration shortcut (the iterator block, yield-return/yield-break).

    Instead, just do what the compiler would have done for you and add some:

    By implementing IEnumerator yourself, you can also add IDisposable

    public class LazyStream : IEnumerable<string>, IDisposable
    {
      LazyEnumerator le;
    
      public LazyStream(FileInfo file, Encoding encoding)
      {
        le = new LazyEnumerator(file, encoding);
      }
    
      #region IEnumerable<string> Members
      public IEnumerator<string> GetEnumerator()
      {
        return le;
      }
      #endregion
    
      #region IEnumerable Members
      System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
      {
        return le;
      }
      #endregion
    
      #region IDisposable Members
      private bool disposed = false;
    
      public void Dispose()
      {
        Dispose(true);
    
        GC.SuppressFinalize(this);
      }
    
      protected virtual void Dispose(bool disposing)
      {
        if (!this.disposed)
        {
          if (disposing)
          {
            if (le != null) le.Dispose();
          }
    
          disposed = true;
        }
      }
      #endregion
    
      class LazyEnumerator : IEnumerator<string>, IDisposable
      {
        StreamReader streamReader;
        const int chunksize = 1024;
        char[] buffer = new char[chunksize];
    
        string current;
    
        public LazyEnumerator(FileInfo file, Encoding encoding)
        {
          try
          {
            streamReader = new StreamReader(file.OpenRead(), encoding);
          }
          catch
          {
            // Catch some generator related exception
          }
        }
    
        #region IEnumerator<string> Members
        public string Current
        {
          get { return current; }
        }
        #endregion
    
        #region IEnumerator Members
        object System.Collections.IEnumerator.Current
        {
          get { return current; }
        }
    
        public bool MoveNext()
        {
          try
          {
            if (streamReader.Peek() >= 0)
            {
              int readCount = streamReader.Read(buffer, 0, chunksize);
    
              current = new string(buffer, 0, readCount);
    
              return true;
            }
            else
            {
              return false;
            }
          }
          catch
          {
            // Trap some iteration error
          }
        }
    
        public void Reset()
        {
          throw new NotSupportedException();
        }
        #endregion
    
        #region IDisposable Members
        private bool disposed = false;
    
        public void Dispose()
        {
          Dispose(true);
    
          GC.SuppressFinalize(this);
        }
    
        protected virtual void Dispose(bool disposing)
        {
          if (!this.disposed)
          {
            if (disposing)
            {
              if (streamReader != null) streamReader.Dispose();
            }
    
            disposed = true;
          }
        }
        #endregion
      }
    }
    

    I didn’t test this, but I think it’s close.

    used like this:

    using (var fe = new LazyStream(new FileInfo("c:\\data.log"), Encoding.ASCII))
    {
      foreach (var chunk in fe)
      {
        Console.WriteLine(chunk);
      }
    }
    

    EDIT: I had totally forgotten to add the try-catch block placements. Oops.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I want use html5's new tag to play a wav file (currently only supported
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.