How to detect if a file exist in a project folder?

别来无恙 提交于 2019-12-14 00:24:06

问题


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#. Thanks.


回答1:


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




回答2:


The question is a little unclear but I get the impression that you're after the path the exe has been installed in?

  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. 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.




回答3:


Use File.Exists(Path Here) If your using a temp path use Path.GetTempPath()

EDIT: Sorry, same answer as above!




回答4:


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.



来源:https://stackoverflow.com/questions/3446915/how-to-detect-if-a-file-exist-in-a-project-folder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!