简体   繁体   中英

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

  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.

Use File.Exists(Path Here) If your using a temp path use 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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