2010-08-10 146 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的位置。

相關問題