I am having a collectio开发者_如何学运维n 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.
精彩评论