[英]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.