簡體   English   中英

使用相對路徑將文件添加到解決方案

[英]Add a file to solution using relative path

我在VS2010中的解決方案中添加了一個文本文件,並將其命名為test.txt。

在文件的屬性中,我已將copy to output設置copy to outputalwaysbuild actioncontent

現在如何在項目中打開此文件? 這樣,如果用戶按下按鈕,它將打開文本文件。

我嘗試了幾種方法,例如File.open("test.txt")System.Diagnostics.Process.Start(file path)) ,但沒有任何效果。

誰能提供一些建議?

由於使用復制輸出文件時,文件與程序位於同一目錄中,因此可以使用:

System.Diagnostics.Process.Start("test.txt");

或基於此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));
    }
}

嗯...我剛剛嘗試了System.Diagnostics.Process.Start("TextFile1.txt") ,它就起作用了。 您可以嘗試以下方法:

        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo.FileName = "TextFile1.txt";
        proc.Start();

如果仍然不起作用,請轉至\\ bin \\ Debug(如果正在Release配置中運行,則轉到\\ bin \\ Release),並確保文本文件實際上與.exe位於同一位置。

那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/zh-CN/library/db5x7c0d.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM