Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

net core 2.0 read file added as resources

I am doing a C# Net Core 2.0 Application...

I have a .sln with several Console projects called PrjA, PrjB, PrjC that will be run in differents ports, port 5000, port 5010, port 5020. They are running in parallel by Console

C:>dotnet PrjA.dll
C:>dotnet PrjB.dll
C:>dotnet PrjC.dll

I have another Library Project called PrjCommon that it is referenced by all three Project. In this Project I want to have a configuration file in common to all three projects.

this file is a json file called portsettings.json.

When i run any of those projects in Debug mode or generating the Publish folder, portsettings.json file is not saved.

In PrjCommon Project I tried to embebed portsettings.json as a file in Resources.resx.

From any of these three projects, I called a Method in PrjCommon that should read portsettings.json file.

I have tried to read this file from Resources.resx in two ways.

First like this

var assembly = Assembly.GetEntryAssembly();
 string[] names = assembly.GetManifestResourceNames();

but names is null.

And Second

var byteArray = Resources.portsettings;

That return a bytes arrays, but i can not transform those byte array into json.

My questions is how can I make it Works. Either to save json file when I Compile those Projects, or, to save it as resources file and be able to read it.

Thanks

like image 315
Diego Avatar asked Feb 14 '18 19:02

Diego


2 Answers

You could read the embedded resources with the following.

public static class EmbeddedResource
{
    public static string[] GetApiRequestFile(string namespaceAndFileName)
    {
        try
        {
            using (var stream = typeof(EmbeddedResource).GetTypeInfo().Assembly.GetManifestResourceStream(namespaceAndFileName))
            using (var reader = new StreamReader(stream, Encoding.UTF8))
                return reader.ReadToEnd().Split(';');
        }

        catch(Exception exception)
        {
            ApplicationProvider.WriteToLog<EmbeddedResource>().Error(exception.Message);
            throw new Exception($"Failed to read Embedded Resource {namespaceAndFileName}");
        }
    }
}

So, in my case I want to read embedded text files that contain URL's that I format, they act as a template primarily. But the logic you're seeking would be that first stream line.

Solution - Opti
Folder   - Resource
File     - RequestUrl.txt

If I had a class where the text file is, the namespace with the specified file would be Opti.Resource.RequestUrl.txt.

Folder Structure

Calling the embedded resource

like image 134
Greg Avatar answered Sep 29 '22 07:09

Greg


I solved saving json file in Debug and Publish directory by setting .json file property Copy to Output Directory to Always as says here.

I have also add Resources file following this tutorial

I do not if it the best way, but it is the simplest.

like image 34
Diego Avatar answered Sep 29 '22 06:09

Diego