![](/img/trans.png)
[英]File.Exists(Path) always return false when get 'string (Path)' from text file
[英]File Exists always return false
ImageURL = String.Format(@"../Uploads/docs/{0}/Logo.jpg", SellerID);
if (!File.Exists(ImageURL))
{
ImageURL = String.Format(@"../Uploads/docs/defaultLogo.jpg", SellerID);
}
每次檢查是否有文件時,都會得到圖像中的默認徽標,是否有超出檢查范圍的內容。
注意:這是網站上引用的類庫
您必須提供物理路徑而不是虛擬路徑(url),才能使用webRequest查找給定url
上是否存在文件。 您可以閱讀本文以查看用於檢查給定url中的資源是否存在的其他方法。
private bool RemoteFileExists(string url)
{
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TURE if the Status code == 200
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false.
return false;
}
}
基於注釋進行編輯 , 在托管url訪問的文件的服務器上運行代碼 。 我假設您的上載文件夾位於網站目錄的根目錄上。
ImageURL = String.Format(@"/Uploads/docs/{0}/Logo.jpg", SellerID);
if(!File.Exists(System.Web.Hosting.HostingEnvironment.MapPath(ImageURL))
{
}
如果它在Web應用程序中,則當前目錄通常不是您認為的那樣。 例如,如果IIS正在為網頁提供服務,則當前目錄可能是inetsrv.exe所在的目錄或臨時目錄。 要獲取Web應用程序的路徑,可以使用
string path = HostingEnvironment.MapPath(@"../Uploads/docs/defaultLogo.jpg");
bool fileExists = File.Exists(path);
http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.mappath.aspx
MapPath會將您提供的路徑轉換為相對於Web應用程序的路徑。 為了確保正確設置路徑,您可以將Trace調試與Trace.Write
一起使用,或將路徑寫入調試文件(使用調試文件的絕對路徑)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.