using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lifetime
{
    // Kod umieszczony w komentarzu gdyż reprezentuje fragment z biblioteki klas.
    //// Listing 7-8
    //public interface IDisposable
    //{
    //    void Dispose();
    //}

    class Examples8_13
    {
        public static void ReadFileWithUsingStatement()
        {
            Directory.CreateDirectory(@"c:\temp");
            if (!File.Exists(@"C:\temp\File.txt"))
            {
                File.AppendAllText(@"C:\temp\File.txt", "Test content");
            }

            // Listing 7-9
            using (StreamReader reader = File.OpenText(@"C:\temp\File.txt"))
            {
                Console.WriteLine(reader.ReadToEnd());
            }

            // Listing 7-10
            {
                StreamReader reader = File.OpenText(@"C:\temp\File.txt");
                try
                {
                    Console.WriteLine(reader.ReadToEnd());
                }
                finally
                {
                    if (reader != null)
                    {
                        ((IDisposable) reader).Dispose();
                    }
                }
            }
        }

        public static void StackUsingStatements()
        {
            // Listing 7-11
            using (Stream source = File.OpenRead(@"C:\temp\File.txt"))
            using (Stream copy = File.Create(@"C:\temp\Copy.txt"))
            {
                source.CopyTo(copy);
            }
        }

        public static void ForEachAndDiposal()
        {
            // Listing 7-12
            foreach (string file in Directory.EnumerateFiles(@"C:\temp"))
            {
                Console.WriteLine(file);
            }

            // Listing 7-13
            {
                IEnumerator<string> e =
                    Directory.EnumerateFiles(@"C:\temp").GetEnumerator();
                try
                {
                    while (e.MoveNext())
                    {
                        string file = e.Current;
                        Console.WriteLine(file);
                    }
                }
                finally
                {
                    if (e != null)
                    {
                        ((IDisposable) e).Dispose();
                    }
                }
            }
        }
    }
}
