简体   繁体   中英

Add a file to solution using relative path

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?

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));
    }
}

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.

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

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