简体   繁体   中英

NET Core Class Library read file in a project folder

I have a NET Core Class Library project that need to read file contents (template file) from a folder within the project. I am using Visual Studio Code

The files are stored as follows:

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

How can I do that? also, will be safe for other OS like Unix and OS?

Hopefully I understand your question correctly.

You can do something similar to:

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

and in your Main you could do something like:

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

    // do something with "contents"
  }
}

This should function properly on a Mac and Linux machine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM