.NET Core类库如何读取项目文件夹中的文件?

6

我有一个.NET Core类库项目,需要从项目内的文件夹中读取文件内容(模板文件)。我正在使用Visual Studio Code。

文件存储如下:

    --Application (root)
    ---Functions (library for functions)
    ---(c# classes)
    ---Services (library for services)
    ---(c# classes)
    ---Templates (templates)
    -----template1.txt
    -----template2.txt
    -----template3.txt

我该怎么做?另外,这样做是否对其他操作系统如Unix和OS也安全?


最好将这些模板嵌入资源中。一旦源代码被编译,二进制文件(包括您的类库)可能会部署在任意文件夹中,从那里没有可靠的方法可以返回到您的源代码文件夹。 - Lex Li
1个回答

8
希望我正确理解了您的问题。可以采用类似以下的方法:

您可以执行类似于以下内容的操作:

using System.IO;

public class MyLocations
{
    public static readonly string App = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

    public static readonly string Templates = Path.Combine(App, "Templates");
}

在你的Main中,你可以做一些像这样的事情:

static void Main(string[] args)
{
  foreach ( var filePath in Directory.EnumerateFiles(MyLocations.Templates) )
  {
    var contents = File.ReadAllText(filePath);

    // do something with "contents"
  }
}

这应该在Mac和Linux机器上正常运行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接