0

我对 c# 和 .net 非常陌生,并试图理解它。

我正在使用如何读取特定文件夹中的所有文件并尝试在下面的代码中应用的解决方案。

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 文件作为文本流?

4

1 回答 1

0

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

我使用了这里的代码:C# - 获取不包括隐藏文件的文件列表

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

这解决了我的问题。

于 2016-06-02T09:13:53.407 回答