【发布时间】:2012-05-12 17:26:42
【问题描述】:
我想检查服务器磁盘上是否存在文件,我正在使用以下代码
if (File.Exists(Server.MapPath("~/Jaram Images/") + Path.GetFileName(product.Pic_Url2)))
{
WriteError("File exist!");
//PdfProdCell = new PdfPCell(iTextSharp.text.Image.GetInstance(Server.MapPath("~/Jaram Images/") + Path.GetFileName(product.Pic_Url2)), true);
}
else
WriteError(Server.MapPath("~/Jaram Images/") + " File doesn't exist!");
但我收到此错误:
public static void WriteError(string errorMessage)
{
try
{
string path = "~/Jaram PDF/PDFS/" + DateTime.Today.ToString("dd-mm-yy") + ".txt";
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
{
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
{
w.WriteLine("\r\nLog Entry : ");
w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
". Error Message:" + errorMessage;
w.WriteLine(err);
w.WriteLine("__________________________");
w.Flush();
w.Close();
}
}
catch (Exception ex)
{
WriteError(ex.Message);
}
}
Log Entry :
05/03/2012 15:50:51
Error in: http://localhost/WebStore/AdminNewAccount.aspx?role=+Administrator. Error Message:C:\inetpub\wwwroot\WebStore\Jaram Images\ File doesn't exist!
我的日志功能喜欢这样
【问题讨论】:
-
文件是否存在于
Server.MapPath("~/Jaram Images/") + Path.GetFileName(product.Pic_Url2))...? -
首先,这不是您从异常中得到的实际错误。其次,您映射同一个文件 3 次,为什么不第一次映射它。此外,不存在的文件实际上是您键入时的目录。最后,调试你的代码,看看真正的问题是什么
-
是的,该文件不存在。当文件不存在时,我想避免此错误,这就是我应用 If 条件的原因。
-
@All 如何检查文件是否存在,以便我可以显示图像,否则,跳过它?