Reputation: 189
I added a text file to my solution in VS2010 and called it test.txt.
In the properties of the file I have set copy to output
: always
and the build action
: content
.
How can I open this file in my project now? So that if a user presses a button it will open up the text file.
I have tried several methods, such as File.open("test.txt")
and System.Diagnostics.Process.Start(file path))
and nothing has worked.
Can anyone offer up some suggestions?
Upvotes: 1
Views: 5384
Reputation: 54552
Since you are using copy to output the file is being placed in the same directory as your program therefore you can use:
System.Diagnostics.Process.Start("test.txt");
or based on this MSDN article:
string path = "test.txt";
using (FileStream fs = File.Open(path, FileMode.Open))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b, 0, b.Length) > 0)
{
textBox1.Text += (temp.GetString(b));
}
}
Upvotes: 3
Reputation: 1863
What about StreamReader?
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
http://msdn.microsoft.com/en-us/library/db5x7c0d.aspx
Upvotes: 2
Reputation: 13429
Hmm... I just tried System.Diagnostics.Process.Start("TextFile1.txt")
and it worked. You can try the following:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "TextFile1.txt";
proc.Start();
If that still doesn't work, go to your \bin\Debug (or \bin\Release if you are running in Release configuration) and make sure that the text file is actually in the same location as your .exe.
Upvotes: 2