Here's a solution.
It relies on getting the FileYouWantToRead copied into the EXE's location where it's findable.
- Create a simple, out-of-the-box WinForms app.
- Right-click the project, select Add then New Folder, name the folder "SomeDir"
- Right-click the new "SomeDir" folder and select Add and then New Item
- In the dialog that pops up, search for "Text", pick Text File and name the file "FileIWantToRead.txt"
- When the file opens, type "This is the file I want to read" and save the file
- Right-click the new "FileIWantToRead.txt" file and choose properties
- In the properties pane, set Build Action to Content and Copy to Output Directory to Copy Always
- Go back to the form designer, drop a button and a label control on the form
- Double-click the button
- In the "Form1.cs" button click handler that opens, put this code:
Form1.cs button click handler:
private void button1_Click(object sender, EventArgs e)
{
var fullExeName = Assembly.GetExecutingAssembly().CodeBase;
if (fullExeName.StartsWith("file://"))
{
fullExeName = fullExeName.Substring(8);
}
var exeDir = Path.GetDirectoryName(fullExeName);
var fileName = Path.Combine(exeDir, "SomeDir", "FileIWantToRead.txt");
var content = File.ReadAllLines(fileName)?.First();
label1.Text = content ?? "Not Found";
}
The "Copy Always" action will cause your text file to get copied to the output EXE's folder. In this case, since it's within the "SomeDir" folder, it will get copied into a "SomeDir" folder under the output folder.
I get the EXE's folder from the executing assembly (i.e., the running exe) and use the various utilities in System.IO
to get the right folder and file names. After clicking the button, the first line of that file will show in the label.