简体   繁体   English

如何检查可执行文件所在目录中是否存在文件?

[英]How to check if a file exists or not in the directory the executable is?

How can I check if a file exists or not in the directory the executable is? 如何检查可执行文件所在目录中是否存在文件? I know how I could code it like this. 我知道我怎么能这样编码。

string path = Application.StartupPath + "config.cfg"
if(!FileExists(path))
{
//create the file
}

But the problem I am facing is that, the file is created every single time, even when the file exists, overwriting the data of the cfg file with the default ones. 但是我面临的问题是,即使文件存在,文件也会每次创建一次,并使用默认文件覆盖cfg文件的数据。

You are not creating the possible file path properly. 您没有正确创建可能的文件路径。 Use Path.Combine like: 使用Path.Combine像这样:

string path = Path.Combine(Application.StartupPath, "config.cfg");

You are getting a path without terminating \\ from Application.StartupPath , later you are concatenating the file name to it, This will create an invalid path, and since that doesn't exist, you check fails. 您将从Application.StartupPath获得一个不终止\\的路径,稍后将其连接到文件名,这将创建一个无效的路径,由于该路径不存在,因此检查失败。

Just to show, the actual reason for getting the error, you can fix your code like: 只是为了显示出导致错误的实际原因,您可以像下面这样修复代码:

string path = Application.StartupPath +"\\"+ "config.cfg";

But, do not use the above code, instead use Path.Combine to join multiple path elements . 但是,请不要使用上面的代码,而应使用Path.Combine来连接多个path元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM