Emanuel
Emanuel

Reputation: 165

Link to local text file in Solution c#

I need to save a set of 20 txt files into my solution so they will be included into the exe file. In such a way I will be able to send to the final users only the executable file and anything else.

I need to use the following function:

File.Copy( sourcePath, @path + "\\FileName.txt");

to copy one of the 20 files into another directory (according to the request of the user). In order to include the 20 txt files into the solution, I created a new folder into the Solution Explorer and I put them into it. Then I selected "Resources" into the option of the single txt file. Let's suppose the name of the folder is FOO and the file is NAME01, then I'm assuming the local address of the single txt file is "\FOO\NAME01.txt". But this is not working, I'm getting an arror from the File.Copy function related to the sourcePath.

Do you have any suggestions? I'm stacked on this problem and I cannot find any solution on the web. Many thanks!

Upvotes: 1

Views: 1675

Answers (1)

John
John

Reputation: 3702

Step 1: add the files to your project

enter image description here

Step 2: make them embedded resource

enter image description here

Step 3: export them to filesystem at runtime:

using System.Reflection;

namespace ConsoleApplication1
{
    class Program4
    {
        public static void Main(string[] args)
        {
            using(var stream = Assembly.GetExecutingAssembly()
                .GetManifestResourceStream("ConsoleApplication1.Files.TextFile1.txt"))
            using (var filestream = System.IO.File.OpenWrite("target.txt"))
            {
                stream.CopyTo(filestream);
                filestream.Flush();
                filestream.Close();
                stream.Close();
            }
        }
    }
}
  • "ConsoleApplication1.Files.TextFile1.txt" comes from:
    • ConsoleApplication1: default namespace of the project containing the files
    • Files.TextFile1.txt: relative path, dotted, inside the dll (look @ screenshot 1)

Upvotes: 2

Related Questions