0

I am very very novice to c# and .net and trying to understand it.

I am using solution from how to read all files inside particular folder and trying to apply in my below code.

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

namespace HowToCopyTextFiles
{
  class Program
  {
    static void Main(string[] args)
    {
      StringBuilder sb = new StringBuilder();
      foreach (string txtName in Directory.GetFiles(@"C:\Users\Environ ment\Desktop\newfolder","*.rtf"))
      {
        using (StreamReader sr = new StreamReader(txtName))
        {
          sb.Append(sr.ReadToEnd());
          sb.AppendLine();
        }
      }
        Console.Write(sb.ToString());
        Console.ReadLine(); 
    }
  }
}

The result is ok but at the end of my test file it shows environment name.

like.

this is content of first file
this is content of second file
↑My environment full name                                            ↑My
environment full name        ↑My environment full name (Yes 3 times)

I am using cs-script, Is it due to that?

While using .txt files, it is working fine. so the question is how to properly open .rtf files as text stream?

Community
  • 1
  • 1
Rahul
  • 10,830
  • 4
  • 53
  • 88

1 Answers1

0

If rtf file is opened, it sometimes saves super hidden(not visible even show hidden file option) temp file as ~filename.rtf which is also read by c#.

I used code from here: C# - Get a list of files excluding those that are hidden

DirectoryInfo directory = new DirectoryInfo(@"C:\temp");
FileInfo[] files = directory.GetFiles();

var filtered = files.Where(f => !f.Attributes.HasFlag(FileAttributes.Hidden));

foreach (var f in filtered)
{
    Debug.WriteLine(f);
}

This solved my problem.

Community
  • 1
  • 1
Rahul
  • 10,830
  • 4
  • 53
  • 88