プロジェクトフォルダに画像のコレクションがあります。
プロジェクトフォルダに画像が存在するかどうかを検出する方法は?私はc#を使用しています。ありがとう。
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"; }
これは、アプリがデプロイされたときに実際に機能します
質問は少し不明確ですが、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を配置する場所であるためです。
File.Exists(Path Here)
一時パスを使用している場合は、Path.GetTempPath()
編集:申し訳ありませんが、上記と同じ答えです!
あなたが使うことができます
string[] filenames = Directory.GetFiles(path);
フォルダ内のファイルのリストを取得し、探しているものが見つかるまで(または見つからないまで)それらを繰り返し処理します
または、try catchブロックでファイルを開こうとして、例外が発生した場合は、ファイルが存在しないことを意味します。