如何打开 .rtf 文件作为文本流

How to open .rtf files as text stream

我是 c# 和 .net 的新手,正在努力理解它。

我正在使用 how to read all files inside particular folder 的解决方案并尝试在我的以下代码中应用。

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(); 
    }
  }
}

结果没问题,但在我的测试文件末尾显示了环境名称。

喜欢。

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)

我正在使用 cs-script,是因为那个吗?

在使用 .txt 文件时,它工作正常。所以问题是如何正确打开 .rtf 文件作为文本流?

如果打开 rtf 文件,它有时会将超级隐藏(即使显示隐藏文件选项也不可见)临时文件保存为 ~filename.rtf,它也可以由 c# 读取。

我使用了这里的代码: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);
}

这解决了我的问题。