我想检查文件是否存在于我的程序所在的同一文件夹中。如果是做某事。我该如何解决?
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)
您的代码不起作用的原因是最后GetDirectoryName
返回 no \
。这甚至被记录在案:
此方法返回的字符串由路径中的所有字符组成,但不包括最后一个
DirectorySeparatorChar
或AltDirectorySeparatorChar
使用Path.Combine
以获得正确的目录分隔字符:
string path = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "tres.xml");
if(File.Exists(path))
{
// ...
}
Run Code Online (Sandbox Code Playgroud)