3

プロジェクトフォルダに画像のコレクションがあります。

プロジェクトフォルダに画像が存在するかどうかを検出する方法は?私はc#を使用しています。ありがとう。

4

4 に答える 4

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

質問のコメントの後に私の答えを編集しました:

コードをコピーしてexits関数を変更しました。これは機能するはずです

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

これは、アプリがデプロイされたときに実際に機能します

于 2010-08-10T07:35:13.903 に答える
2

質問は少し不明確ですが、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を配置する場所であるためです。

于 2010-08-12T09:23:27.010 に答える
0

File.Exists(Path Here)一時パスを使用している場合は、Path.GetTempPath()

編集:申し訳ありませんが、上記と同じ答えです!

于 2010-08-12T08:41:13.487 に答える
-3

あなたが使うことができます

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

フォルダ内のファイルのリストを取得し、探しているものが見つかるまで(または見つからないまで)それらを繰り返し処理します

または、try catchブロックでファイルを開こうとして、例外が発生した場合は、ファイルが存在しないことを意味します。

于 2010-08-10T07:38:25.497 に答える