如何在Visual Studio Project中获取或设置动态绝对文件路径?

问题描述 投票:0回答:1
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");

上面的代码是一个简单的程序,它检查完整的文件路径是否存在,但是我想要的不是复制粘贴文件的完整路径,而是希望它像字符串一样>> string path = "..\Image\Boruto_logo.png"即使我将项目转移到另一台计算机上,它仍然可以正常运行

c# visual-studio-2015 path
1个回答
1
投票

在项目文件夹中创建新的Images文件夹(这是完全可选的),然后将图像添加到其中。 Right click to folder-> Add-> Existing items-> Select your image

enter image description here

现在将Copy to output directory属性更改为始终复制

enter image description here

现在使用下面的相对路径访问此文件。

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");

这样,即使您在另一台计算机上运行代码,它也能正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.