How to determine if a file exists in a project folder?

I have a collection of images in a project folder.

How to determine if an image exists in the project folder? I am using C #. Thank.

+3
source share
4 answers
if (System.IO.File.Exists("pathtofile"))
  //it exist
else
  //it does not exist

CHANGED MY RESPONSE AFTER COMMENT QUESTION:

I copied the code and changed the exit 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 really work when your application is deployed.

+11
source

The question is a bit unclear, but I get the impression that you are after the path on which exe was installed?

  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. dir- , , VS exe.

+1

Use File.Exists(Path Here)if in your use of a temporary way usePath.GetTempPath()

EDIT: Sorry, same answer as above!

0
source

you can use

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

to get a list of files in a folder and then scroll through them until you find what you are looking for (or not)

or you can try to open the file in a try catch block, and if you get an exception, it means that the file does not exist.

-3
source

Source: https://habr.com/ru/post/1758862/


All Articles