简体   繁体   中英

How to get relative path of file which is in project folder?

我尝试使用@"~\\TestData\\Test.xml" ,它试图从bin/debug而不是项目文件夹中获取文件。

Go to Solution explorer -> right click on TestData folder and choose "Add New Item"

Choose "Resources file", rename it to Resource and click "Add".

在此处输入图片说明

You will get this screen (It can also be opened by double click on "Resource.resx in the solution explorer) 在此处输入图片说明

Give name to the file and put the relative path in the value (may require one level up or down). To get the path you can now use

string path = Resource.XMLFile;

You can achieve this by getting the parent of the current directory, using the Directory class in System.IO namespace. See code example.

using System.IO;

namespace ConsoleApplication15
{
    class Program
    {
        static void Main(string[] args)
        {
            var projectFolder = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
            var file = Path.Combine(projectFolder, @"TestData\Test.xml");
        }
    }
}

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