【问题标题】:How to open .rtf files as text stream如何将 .rtf 文件作为文本流打开
【发布时间】:2016-06-01 06:40:08
【问题描述】:

我对 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文件所致。
  • 您可以尝试使用记事本处理普通的 .txt 文件吗?
  • 我会使用记事本打开第三个文件并检查其内容。
  • 没有第三个文件。
  • @dumb_terminal:是的,这似乎是由于 rtf 文件。 .txt 文件给出了正确的字符串。

标签: c# .net rtf cs-script


【解决方案1】:

如果打开 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);
}

这解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 2020-06-24
    • 1970-01-01
    相关资源
    最近更新 更多