【问题标题】:How to check File Exists c#如何检查文件是否存在c#
【发布时间】:2017-04-24 18:43:48
【问题描述】:

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

private void button12_Click(object sender, EventArgs e)
{

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

}

【问题讨论】:

标签: c# winforms file


【解决方案1】:

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

此方法返回的字符串由 到 但不包括最后一个 DirectorySeparatorCharAltDirectorySeparatorChar

使用Path.Combine 获取正确的目录分隔符:

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

【讨论】:

    【解决方案2】:

    你可以简单地使用:

    File.Exists("tres.xml");
    

    这会检查 .exe 的当前目录

    【讨论】:

    • 请注意,它是 .exe 的当前目录,这意味着 bin\Debug(如果您从 VS 运行)而不是您的项目根目录。
    猜你喜欢
    • 1970-01-01
    • 2019-03-16
    • 2016-02-23
    • 2011-11-01
    • 1970-01-01
    • 2018-01-24
    相关资源
    最近更新 更多