简体   繁体   中英

How do I add a custom text file to a visual studio project?

I'm building a typing application, and would like to add text files containing various commonly used words to the project, which can later be read from. However, when I go to Project -> Add Existing Item, there is only the option to add VB code files to the project. Is there a way to add text files to the project, or will I have to import the data from the file at runtime?

Project Resource (Resx) Version:

This version is slightly easier to work with for your example!

  • Right Click on your project
  • Select Properties
  • Goto the Resources Section
  • You will see a drop down in the top left corner of the Resources Secion, shown in the Screenshot below.
  • Select "Files" from the DropDown.
  • Click the Add Resource Button.
  • A Select File Dialog box will be shown.
  • Select your file
  • Save Your Project

Resx资源

Now to access this file simply use something like...

Dim content As String = My.Resources.mytextfile

Note: You don't need the extension, and this will be strongly typed also!

Embedded Resource Version:

  • Right Click on your Project.
  • Goto Add->Existing Item.
  • At the bottom right will be a dropdown (Next to the filename).
  • Select "All Files (*.*)"
  • Browse to your files' location.
  • Add the File.

选择所有文件

Once you have added you file(s), selecting the file(s) in the solution explorer window will allow you to select their "Build Action". You can select either Content, or Embedded Resource from the options.

  • Content : Allows you to retrieve a file (in same dir as assembly) as a stream via Application.GetContentStream( uri ). For this method to work, it needs a AssemblyAssociatedContentFile custom attribute which VS graciously adds when you mark a file as "Content"
  • Embedded resource : embeds the file in an exclusive assembly manifest resource.

Taken from; https://stackoverflow.com/a/145769/1305169

If you select Embedded Resource, then to read your text file, you can use code such as;

Dim executing_assembly As System.Reflection.Assembly = _
    Me.GetType.Assembly.GetEntryAssembly()

' Get our namespace.
Dim my_namespace As String = _
    executing_assembly.GetName().Name.ToString()

' Load a text file.
Dim text_stream As Stream = _
    executing_assembly.GetManifestResourceStream(my_namespace _
    + ".text1.txt")
If Not (text_stream Is Nothing) Then
    Dim stream_reader As New StreamReader(text_stream)
    Label1.Text = stream_reader.ReadToEnd()
    stream_reader.Close()
End If

Taken from: http://www.vb-helper.com/howto_net_embedded_resources.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM