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

Ops*_*Ops 1 c# file winforms

我想检查文件是否存在于我的程序所在的同一文件夹中。如果是做某事。我该如何解决?

private void button12_Click(object sender, EventArgs e)
{

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

}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 6

您的代码不起作用的原因是最后GetDirectoryName返回 no \。这甚至被记录在案:

此方法返回的字符串由路径中的所有字符组成,但不包括最后一个 DirectorySeparatorCharAltDirectorySeparatorChar

使用Path.Combine以获得正确的目录分隔字符:

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