简体   繁体   English

如何检查文件是否存在c#

[英]How to check File Exists c#

I would like to check file exists in the same folder where is my program. 我想检查文件在我的程序所在的文件夹中是否存在。 If is do something. 如果是做某事。 How i can fix that ? 我该如何解决?

private void button12_Click(object sender, EventArgs e)
{

    if (File.Exists(Path.GetDirectoryName(Application.ExecutablePath) + "tres.xml"))
         Upload("tres.xml");

}

The reason why your code doesn't work is that GetDirectoryName returns no \\ at the end. 您的代码无法正常工作的原因是, GetDirectoryName返回\\ That's even documented: 甚至记录在案:

The string returned by this method consists of all characters in the path up to but not including the last DirectorySeparatorChar or AltDirectorySeparatorChar 此方法返回的字符串包含路径中的所有字符,直到但不包括最后的 DirectorySeparatorCharAltDirectorySeparatorChar

Use Path.Combine to get the correct directory separator char: 使用Path.Combine获取正确的目录分隔符char:

string path =  Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "tres.xml");
if(File.Exists(path))
{
    // ...
}

You can just simply use: 您可以简单地使用:

File.Exists("tres.xml");

This checks the current directory of your .exe 这将检查您的.exe的当前目录

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

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