简体   繁体   English

使用相对路径将文件添加到解决方案

[英]Add a file to solution using relative path

I added a text file to my solution in VS2010 and called it test.txt. 我在VS2010中的解决方案中添加了一个文本文件,并将其命名为test.txt。

In the properties of the file I have set copy to output : always and the build action : content . 在文件的属性中,我已将copy to output设置copy to outputalwaysbuild actioncontent

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. 我尝试了几种方法,例如File.open("test.txt")System.Diagnostics.Process.Start(file path)) ,但没有任何效果。

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 : 或基于此MSDN文章

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. 嗯...我刚刚尝试了System.Diagnostics.Process.Start("TextFile1.txt") ,它就起作用了。 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. 如果仍然不起作用,请转至\\ bin \\ Debug(如果正在Release配置中运行,则转到\\ bin \\ Release),并确保文本文件实际上与.exe位于同一位置。

What about StreamReader? 那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 http://msdn.microsoft.com/zh-CN/library/db5x7c0d.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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