【问题标题】:How to detect if a file exist in a project folder?如何检测项目文件夹中是否存在文件?
【发布时间】:2011-03-27 16:34:34
【问题描述】:

我的项目文件夹中有一组图像。

如何检测我的项目文件夹中是否存在图像?我正在使用 c#。谢谢。

【问题讨论】:

  • 您能否准确指定何时需要检测这些?我们说的是编译前,还是编译后的程序运行时?
  • 我有一个项目列表视图,数据绑定到本地文件夹 Z 上的文件列表,其中包含 .doc、.xls 等各种文件。在我的项目(解决方案)文件中,我有一个包含图像文件集合的文件夹,即 doc.png、xls.png 等。我现在要做的是循环文件夹 Z 中的文件,检测文件类型,并尝试返回:string type = Path .GetExtension(文件路径);字符串路径=@“图像/”+类型+“.png”; if(Exist(path)) { 返回路径; } 其他 { 返回 @"image/other.png"; } 因为文件位于我的解决方案文件夹中,所以我不确定它在部署后是否有效。

标签: c# file-exists


【解决方案1】:
if (System.IO.File.Exists("pathtofile"))
  //it exist
else
  //it does not exist

在问题评论后编辑我的答案:

我复制了代码并更改了退出函数,这应该可以工作

string type = Path.GetExtension(filepath); 
string path = @"image/" + type + ".png"; 
//if(System.IO.File.Exists(path)) I forgot to use the full path
if (System.IO.File.Exists(Path.Combine(Directory.GetCurrentDirectory(), path)))
 { return path; } 
else 
 { return @"image/other.png"; }

这确实会在您的应用部署后工作

【讨论】:

  • 如果您还需要获取时间戳和其他基本信息,另一种方法是使用FileInfo
  • @Steven:如果您想要文件的信息,这是正确的,但如果您只需要知道文件是否存在,则 File.Exists 具有更好的性能
  • 是的,这就是为什么我建议您在需要其他信息时将其作为替代方案,而不是作为一般替代方案。
  • @VHanded:如果此答案对您有帮助,请将答案标记为已接受。然后答案被标记,其他人可以看到问题已解决
  • 对不起,也许我的问题不够清楚,但这不是我要求的。我刚刚在我的问题的评论中更新了我的问题,但是编辑器都挤在一起了。
【解决方案2】:

这个问题有点不清楚,但我觉得你在追求 exe的安装路径?

  class Program
  {
    static Dictionary<string, string> typeImages = null;

    static string GetImagePath(string type)
    {
      if (typeImages == null)
      {
        typeImages = new Dictionary<string, string>();
        string appPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
        string path = Path.Combine(appPath, @"image/");
        foreach (string file in Directory.GetFiles(path))
        {
          typeImages.Add(Path.GetFileNameWithoutExtension(file).ToUpper(), Path.GetFullPath(file));
        }
      }

      if (typeImages.ContainsKey(type))
        return typeImages[type];
      else
        return typeImages["OTHER"];
    }

    static void Main(string[] args)
    {
      Console.WriteLine("File for XLS="+GetImagePath("XLS"));
      Console.WriteLine("File for ZZZ=" + GetImagePath("ZZZ"));
      Console.ReadKey();
    }
  }

这将为您提供一个图像文件夹,该文件夹将位于安装 exe 的任何位置。 在开发环境中,您必须在应用程序路径中的 debug 和 release 下创建一个图像目录,因为这是 VS 放置 exe 的位置。

【讨论】:

    【解决方案3】:

    使用File.Exists(Path Here) 如果您使用临时路径,请使用Path.GetTempPath()

    编辑:对不起,和上面的答案一样!

    【讨论】:

      【解决方案4】:

      你可以使用

      string[] filenames = Directory.GetFiles(path);
      

      获取文件夹中文件的列表,然后遍历它们,直到找到您要查找的内容(或不查找)

      或者您可以尝试在 try catch 块中打开文件,如果遇到异常则表示该文件不存在。

      【讨论】:

      • 不如File.ExistsFileInfo.Exists 方法高效。
      • 效率真的低吗?您可以以惰性评估方式使用它,或者在启动时获取文件并保留列表。
      猜你喜欢
      • 2016-05-20
      • 1970-01-01
      • 2011-11-15
      • 2010-12-10
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 2013-03-12
      • 2013-04-12
      相关资源
      最近更新 更多