2010-08-10 143 views
3

我有我的项目文件夹中的图像集合。如何检测项目文件夹中是否存在文件?

如何检测图像是否存在于我的项目文件夹中?我正在使用C#。谢谢。

+0

你能指定什么时候你需要检测这些?我们在编译之前还是编译的程序正在运行? – 2010-08-10 07:38:05

+0

我有一个项目列表视图,数据绑定到我的本地文件夹Z上的文件列表,包括各种文件如.doc,.xls等。 在我的项目(解决方案)文件中,我有一个文件夹图像文件的收集,即doc.png,xls.png等 我现在要做的是循环文件夹Z中的文件,检测文件类型,并尝试返回如下: string type = Path。 GetExtension(文件路径); string path = @“image /”+ type +“.png”; (存在(路径)) { return path; } else { return @“image/other.png”; } 因为这些文件位于我的解决方案文件夹中,所以我不确定它会在部署之后起作用。 – VHanded 2010-08-12 05:57:57

回答

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

编辑我的回答这个问题的后评论:

我复制的代码,改变了退出功能,这应该工作

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

这的确会工作时,你的应用程序部署

+0

另一种方法是使用'FileInfo',如果您还需要获取时间戳和其他基本信息。 – 2010-08-10 07:39:53

+0

@Steven:这是正确的,如果你想要的文件的信息,但File.Exists有更好的性能,如果你只需要知道是否存在 – 2010-08-10 07:50:52

+0

是的,这就是为什么我建议它作为替代如果你也要去需要额外的信息,而不是一般的替代品。 – 2010-08-10 08:40:45

-3

你可以使用

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

得到的文件列表中的文件夹中,然后遍历它们,直到你找到你想找的(或不)

,或者你可以尝试在try catch块打开该文件,如果你得到它意味着该文件不存在的异常。

+0

这些都不是好主意。 – 2010-08-10 07:39:23

+0

效率不如'File.Exists'或'FileInfo.Exists'方法。 – tdammers 2010-08-10 07:44:49

+0

效率真的很低?你会以懒惰的评估方式使用它,或者在启动时获取文件并保留列表。 – 2010-08-12 08:45:20

0

使用File.Exists(Path Here)如果您使用临时路径使用Path.GetTempPath()

编辑:对不起,相同的答案以上!

1

这个问题有点不清楚,但我得到的印象是,你在 之后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(); 
    } 
    } 

这将给你一个图像文件夹,将在任何地方安装exe。 在开发环境中,您必须在应用程序路径下调试并释放图像目录,因为这是VS放置exe的位置。

相关问题