NET Core 类库读取项目文件夹中的文件

You*_*usi 6 c# .net-core

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

文件存储方式如下:

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

我怎样才能做到这一点?另外,对于 Unix 和 OS 等其他操作系统是否安全?

小智 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");
}
Run Code Online (Sandbox Code Playgroud)

在你的Main你可以做类似的事情:

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

    // do something with "contents"
  }
}
Run Code Online (Sandbox Code Playgroud)

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