簡體   English   中英

C#如何在沒有長路徑的情況下在與運行程序相同的位置上繪制文件

[英]C# how do I draw on files in the same location as i'm running the program without a long path

到目前為止,我還沒有發現任何可以讓我的程序訪問與其所在文件夾中的文本文件的內容。 例如:如果我的文件在C:/ testingfolder中,我將需要使用C:/testingfolder/filenames.txt來訪問其他文件,但與此相關的問題是有時它不會在c:/ testingfolder中,但可能是在E:/ importantfiles或F:/ backup中,它需要從所有這些文件中運行。

如果有人可以解釋或提供代碼,說明如何將更長的路徑轉換成可以回答我的問題的“相同文件夾”路徑。

使用Environment.CurrentDirectory您可以獲取正在執行的進程的路徑,然后應使用System.IO.Path.Combine()方法將該路徑與文件名連接起來,然后您將獲得以下位置的絕對位置:您的文件。

您需要使用System.IOSystem.Text

using System;
using System.IO;
using System.Text;

然后

static void Main(string[] args)
{
    string line = "";
    // look for the file "myfile.txt" in application root directory
    using (StreamReader sr = new StreamReader("myfile.txt"))
    {
        while ((line = sr.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
    }

    Console.ReadKey();
}

暫無
暫無

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

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