Read file that is on Solution in C#

Asked

Viewed 1,270 times

1

I created a file on Solution of my project. How do I read this file? He must stay in Solution because when compiling it should be packaged in the . exe.

  • Read here and improve your question. http://answall.com/help/how-to-ask

  • What kind of file? How will it be used in Solution? A recent case that I had to do this is move up one template e-mail, for this case I include it as Resource in the project.

  • It can be any type of file, my problem and that whenever I change I need to change this file, this change goes to a file that is in the exe folder. I need to change exactly what is in the hierarchy of Solution, and when reading, it has to be exactly it too

  • Dude, you need to tell me what kind of file you want to use. I can tell you the following, your file needs to be a Resource, but it is necessary a different treatment for each type of file.

  • right, I’ll be using this project a . txt

1 answer

2


First you need to configure the file to be copied to the bin in the build of his Solution:

  1. Right click on the file > Properties (or select the file and press F4;
  2. In Build Action, select Content;
  3. In Copy to Output Directory, select or Copy Always or Copy if newer.

If it is a text file, you can read this file with the following command:

var reader = new StreamReader(@"meuarquivo.txt");

For files inside the executable, it is basically the translation of this article: https://support.microsoft.com/en-us/kb/319292. I will explain briefly.

  1. Right click on the file > Properties (or select the file and press F4;
  2. In Build Action, select Embedded Resource;

Accessing

using System.IO;
using System.Reflection;

try
{
    var assembly = Assembly.GetExecutingAssembly();
    var imageStream = assembly.GetManifestResourceStream("MeuArquivo.txt");
}
catch
{
    throw new Exception("Erro acessando arquivo de resource.");
}
  • Right, then how do I get this file to be packaged next to . exe, without needing this file to be visible in the folder ?

  • 1

    If he is part of the exe, then he needs to be a Resource. Would you like me to expand the answer to Resource?

  • Yes, please! Thank you

  • @Jetersonmirandagomes There it is.

  • 1

    Thanks partner, thank you so much for your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.