Search code examples
c#streamreader

Read in from multiple type files all in different locations


In C# using StreamReader, I have to extract the data from multiple files. Here's the code I have so far. It's not exactly correct and I have to be more specific with it and add more to it yet. I need to select various individual files based on a date and time they all have in common. So only the files with a common inputted date and time will be selected for extraction. The problem is the files are different types e.g. text, xml and html and they may possible be in different locations. I have to display all the extracted data together. Any help would be greatly appreciated. Thank you.

    private void btnLoad_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var files = Directory.EnumerateFiles("D:\\path", "*.*", SearchOption.AllDirectories)
            .Where(s => s.EndsWith(".txt") || s.EndsWith(".xml"));

            using (StreamReader sr = new StreamReader("files")).
            {
                string line;

                while ((line = sr.ReadLine()) != null)
                {
                    lbDisplay.Items.Add(line);
                }
            }
        }
        catch (Exception ex)
        {
            // Let the user know what went wrong
            MessageBox.Show("The file could not be read: ");
            MessageBox.Show(ex.Message);
        }
    }

Solution

  •     IEnumerable<string> fileContents = Directory.EnumerateFiles("E:", "*.*", SearchOption.TopDirectoryOnly)
                .Select(x => new FileInfo(x))
                .Where(x => x.CreationTime > DateTime.Now.AddHours(-1) || x.LastWriteTime > DateTime.Now.AddHours(-1))
                .Where(x => x.Extension == ".xml" || x.Extension == ".txt")
                .Select(file => ParseFile(file));
    
        private string ParseFile(FileInfo file)
        {
            using (StreamReader sr = new StreamReader(file.FullName))
            {
                string line;
                string endResult;
                while ((line = sr.ReadLine()) != null)
                {
                    //Logic here to determine if this is the correct file and append accordingly
                    endResult += line + Environment.Newline;
                }
                return endResult;
            }
        }
    

    This will get you a list of files then pass the FileInfo object to a method to read the contents, which is where you will need to add your logic to determine if you have the correct file. If so, then start appending your lines to the lblDisplay.