简体   繁体   中英

How to get or setup dynamic absolute File Path in Visual Studio Project?

string path = @"c:\users\user\documents\visual studio 2015\Projects\PRACTICE\PRACTICE\Image\Boruto_logo.png";

        if (File.Exists(path))
            MessageBox.Show("Exists");
        else
            MessageBox.Show("Not Exist");

The code above is a simple program that checks if the full file path exists but what I want is instead of copy-pasting the full path of the file, I want it like the string to be like this >> string path = "..\\Image\\Boruto_logo.png" so that even I transfer my project to another computer it will still run correctly

Create new Images folder in your project folder (this is completely optional) and add your image to it. Right click to folder -> Add -> Existing items -> Select your image

在此处输入图片说明

Now change Copy to output directory property to Copy Always .

在此处输入图片说明

Now use below relative path to access this file.

using System.IO;

...
//GetCurrentDirectory() will give you current executable directory.
//Combine with current directory with your resource
string path = Path.Combine(Directory.GetCurrentDirectory(), @"Images\Boruto_logo.png");

if (File.Exists(path))
    Console.WriteLine("Exists");
else
    Console.WriteLine("Not Exist");

In this way, even if you run your code on another computer it will work fine.

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