简体   繁体   English

如何检测项目文件夹中是否存在文件?

[英]How to detect if a file exist in a project folder?

I am having a collection of images in my project folder. 我在项目文件夹中有一组图像。

how to detect if a image exist in my project folder? 如何检测我的项目文件夹中是否存在图像? I am using c#. 我正在使用c#。 Thanks. 谢谢。

if (System.IO.File.Exists("pathtofile"))
  //it exist
else
  //it does not exist

EDITED MY ANSWER AFTER THE COMMENT OF THE QUESTION: 在提出问题之后编辑了我的答案:

I copied the code and changed the exits function, this should work 我复制了代码并更改了退出功能,这应该可行

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"; }

This will indeed work when your app is deployed 在部署应用程序时,这确实有效

The question is a little unclear but I get the impression that you're after the path the exe has been installed in? 问题有点不清楚,但我得到的印象是你已经安装了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();
    }
  }

This will give you an image folder that will be wherever the exe is installed. 这将为您提供一个图像文件夹,该文件夹将安装在exe的任何位置。 In the dev environment, you'll have to create an images dir under debug and release in the app path because that's where VS puts the exe's. 在开发环境中,你必须在app路径下创建一个调试和释放的图像目录,因为这就是VS放置exe的地方。

Use File.Exists(Path Here) If your using a temp path use Path.GetTempPath() 使用File.Exists(Path Here)如果您使用临时路径使用Path.GetTempPath()

EDIT: Sorry, same answer as above! 编辑:对不起,同上面的答案!

you could use 你可以用

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

to get a list of the files in the folder and then iterate through them until you find what your looking for (or not) 获取文件夹中的文件列表,然后遍历它们,直到找到您要查找的内容(或不查找)

or you could try to open the file in a try catch block and if you get an exception it means the file does not exist. 或者您可以尝试在try catch块中打开该文件,如果您收到异常,则表示该文件不存在。

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

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