Venkatesh R
Venkatesh R

Reputation: 530

Create file while running C# using template file which is added in the project

Have added a text file in my C# project and it contains static value (around 300 lines). Will it possible to create a txt in specified path and file name using template file content which is attached in the project. When ever the binary runs it has to create a txt in the specified path with the content available in the template file.

enter image description here

Upvotes: 1

Views: 4277

Answers (2)

George Dzhgarkava
George Dzhgarkava

Reputation: 56

There are two steps:

1) Add your template file to project as Embedded Resource.

Click on QAXXXXVBSFile.txt in Solution Explorer and set Build Action to Embedded Resource

Embedded Resource

2) Read this resource by using GetManifestResourceStream() and write data in the new text file.

using System;
using System.IO;
using System.Reflection;

namespace AutomateDigicall
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get current assembly
            var assembly = Assembly.GetExecutingAssembly();
            var resourceName = "AutomateDigicall.QAXXXXVBSFile.txt";

            string template = String.Empty;

            // Read resource from assembly
            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            using (StreamReader reader = new StreamReader(stream))
            {
                template = reader.ReadToEnd();
            }

            // Write data in the new text file
            var filePath = "C:\\TestFolder\\myFileName.txt";
            using (TextWriter writer = File.CreateText(filePath))
            {
                writer.WriteLine("Text from template below:");
                writer.WriteLine(template);
            }
        }
    }
}

Upvotes: 3

Ben Jackson
Ben Jackson

Reputation: 1138

The best solution is probably to add the file as a Project Resource. Right click on your C# project and select Properties, then Resources. Click the link to add a Resources file if prompted, then select the option to add your file as a Proejct Resource. You can then access the file content in your C# code via [Project Namespace].Properties.[File Name].

Upvotes: 1

Related Questions