I need to read a file from my resources and add it to a list. my code:
private void Form1_Load(object sender, EventArgs e) { using (StreamReader r = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("myProg.myText.txt"))) { //The Only Options Here Are BaseStream & CurrentEncoding } }
Ive searched for this and only have gotten answers like "Assembly.GetExecutingAssembly...."
but my program doesnt have the option of Assembly.?
How to open a TXT file. You can open a TXT file with any text editor and most popular web browsers. In Windows, you can open a TXT file with Microsoft Notepad or Microsoft WordPad, both of which come included with Windows.
For reading and writing to a text file, we use the functions fprintf() and fscanf(). They are just the file versions of printf() and scanf() . The only difference is that fprintf() and fscanf() expects a pointer to the structure FILE.
Text files in C are straightforward and easy to understand. All text file functions and types in C come from the stdio library. When you need text I/O in a C program, and you need only one source for input information and one sink for output information, you can rely on stdin (standard in) and stdout (standard out).
Use the fscanf Function to Read File Line by Line in C The fscanf function is part of the C standard library formatted input utilities. Multiple functions are provided for different input sources like scanf to read from stdin , sscanf to read from the character string, and fscanf to read from the FILE pointer stream.
Try something like this :
string resource_data = Properties.Resources.test; List<string> words = resource_data.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries).ToList();
Where
You need to include using System.Reflection;
in your header in order to get access to Assembly. This is only for when you mark a file as "Embedded Resource" in VS.
var filename = "MyFile.txt" System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNameSpace." + filename));
As long as you include 'using System.Reflection;' you can access Assembly like this:
Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace." + filename);
Or if you don't need to vary filename just use:
Assembly.GetExecutingAssembly().GetManifestResourceStream("YourNamespace.MyFile.txt");
The full code should look like this:
using(var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("myProg.myText.txt")) { string line; while ((line = reader.ReadLine()) != null) { // Do some stuff here with your textfile } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With