How to get a text file that will be part of my assembly?

I wrote a program that reads from text files and can create them to load and save data. I have several files, which are the "standard" data, which are loaded immediately after the program starts. Files are loaded with a static link. My code works fine before publishing it, but obviously when I publish it, static links no longer work. I don't know how to add default data to the assembly as text files so that I can reference it after the assembly.

I suppose I can create a program and have some kind of folder that accompanies an executable file with default data files that I can easily reference, but I don't know how to do it (or if there is a better way).

Below is the code that I use to read from a file. Currently, the default data file name is passed statically to the subroutine and used to identify the file to read, so I would like to have a published file with which I can do the same with.

Try Dim sr As New IO.StreamReader(FileName) Dim strLine As String = "" Do Until sr.EndOfStream strLine = sr.ReadLine 'Code that interprets the data in the file 

Note. I tried to add the files as "Resources", but I can not refer to the file as a text file; I can only get a massive wall of text contained in a document that will not work with the above code (unless, of course, I am missing something).

If you could clarify:

  • How to add a file to the assembly so that I can get it collectively by file name?
  • How will my code link to files (for example, "My.Resources.filename"?) In the final assembly?
+6
source share
1 answer

You can add a file to the assembly as a content file or inline resource.

For the content file, set the "Assembly action" parameter to the "content" file and "Copy to output directory" in "Always copy" in the file properties. Then you can access the file as follows:

 FileName = Application.StartupPath() = + FileName Dim sr As New IO.StreamReader(FileName) ... 

To insert a file as a resource, you need to set the action "Build action" in "Embedded resource" and "Copy to output directory" to "false". This one has access to embedded resources. The code would be something like this:

 Dim sr As StreamReader Dim thisAssembly As Assembly thisAssembly = Assembly.GetExecutingAssembly() sr = New StreamReader(thisAssembly.GetManifestResourceStream("NameSpace." + FileName)) Dim strLine As String = "" Do Until sr.EndOfStream strLine = sr.ReadLine 'Code that interprets the data in the file ... 

Replace NameSpace the namespace of your application (Project Properties -> Application -> root namespace)

You also need to add Imports System.Reflection to the top of your code file.

Using an embedded resource has the advantage of having fewer files to manage, and you don't need to track paths.

+8
source

Source: https://habr.com/ru/post/945634/


All Articles