簡體   English   中英

如何檢測項目文件夾中是否存在文件?

[英]How to detect if a file exist in a project folder?

我在項目文件夾中有一組圖像。

如何檢測我的項目文件夾中是否存在圖像? 我正在使用c#。 謝謝。

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

在部署應用程序時,這確實有效

問題有點不清楚,但我得到的印象是你已經安裝了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的任何位置。 在開發環境中,你必須在app路徑下創建一個調試和釋放的圖像目錄,因為這就是VS放置exe的地方。

使用File.Exists(Path Here)如果您使用臨時路徑使用Path.GetTempPath()

編輯:對不起,同上面的答案!

你可以用

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

獲取文件夾中的文件列表,然后遍歷它們,直到找到您要查找的內容(或不查找)

或者您可以嘗試在try catch塊中打開該文件,如果您收到異常,則表示該文件不存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM