Exemple #1
0
        /// <summary>
        /// "Factory" method that creates a WidgetCollection object from
        /// the contents of the specified file.
        /// </summary>
        /// <param name="path">Path and filename of a comma separated value (CSV) file
        /// from which to read data for creating Widget objects.</param>
        /// <returns>A collection of Widget objects.</returns>
        public static WidgetCollection CreateFromCSVFile(string path)
        {
            if (!File.Exists(path))
            {
                return(null);
            }

            WidgetCollection result = new WidgetCollection();
            StreamReader     reader;

            try
            {
                // Open the file.
                reader = new StreamReader(path);

                // For each line from the file, create a Widget object and
                // add it to the result collection.
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    Widget widget = Widget.CreateFromCSV(line);
                    if (widget != null)
                    {
                        // Result is a WidgetCollection object, which has an
                        // Add method inherited from List<>.
                        result.Add(widget);
                    }
                }

                // Don't forget to close the file!
                reader.Close();
            }
            catch (Exception)
            {
                return(null);
            }

            return(result);
        }
Exemple #2
0
        static void Main(string[] args)
        {
            string dataPath = "..\\..\\Widgets.csv";

            if (!File.Exists(dataPath))
            {
                Console.WriteLine("Make sure Widgets.csv is in the project's base path.");
            }
            else
            {
                WidgetCollection widgets = WidgetCollection.CreateFromCSVFile(dataPath);

                if (widgets == null)
                {
                    Console.WriteLine("Problem reading file.");
                }
                else
                {
                    widgets.PrintSummary();
                }
            }
        }