C# 在内容中查找不存在的文件而不是显示内容

C# looks for non-existent file in contents rather than displaying contents

我正在用 C# 尝试文件 I/O(因为我是初学者,所以之前完全没有这样做过)。我在解决方案的资源中放置了一个包含“一些文本”(字面意思)的简单文本文件,根据在线教程编写了一些代码,然后按 F5 进行构建。我期待“一些文本”出现在控制台中 window,但出现了异常!

Could not find file 'F:\VS\FileTesting\FileTesting\bin\Debug\some text'.

正如我上面所说,“一些文本”是文件的内容,它的名字是“important.txt”

这是我使用的代码:

try
{
     /* using (StreamReader reader = new StreamReader(Properties.Resources.important))
     {
          string line;

          while ((line = reader.ReadLine()) != null)
          {
              Console.WriteLine(line);
          }
     } */
     string contents = File.ReadAllText(Properties.Resources.important);
     Console.WriteLine(contents);
     Console.WriteLine("Contents displayed successfully.");
     Console.ReadKey();
}
catch (Exception e) {
    MessageBox.Show("An error occured. Exception: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

(上面的注释部分来自另一个post ,它解释了如何逐行读取文件)

根据@JonSkeet 下面的评论,我想我找到了原因:它看起来像 File.ReadAllText 读取 Properties.Resources.important 的内容并将其视为文件名而不是预期的文本。 “一些文本”是它唯一能找到的东西,因此它在构建目录中搜索一个不存在的具有该名称的文件。我所做的是将原始文件重命名为“pointer.txt”,在其中写入“important.txt”并将其用作指向我要读取的文件的指针。

我可以让它读取外部文件,但我想要我的资源中的文件。另外,我似乎无法将其设为嵌入式 - 该选项被禁用。那也有什么关系吗?

感谢任何帮助。

您不需要使用 File 方法来读取资源的内容。 File 方法用于从文件系统读取文件。

要访问资源的内容,只需写Properties.Resources.important。您可以 Console.WriteLine(Properties.Resources.important) 将资源的内容写入控制台。