2015-07-01 64 views
5

我找到了解決方案,但我沒有正確的路徑。asp從服務器路徑目錄中選擇隨機文件

select random file from directory

public string getrandomfile2(string path) 
{ 
    string file = null; 
    if (!string.IsNullOrEmpty(path)) 
    { 
     var extensions = new string[] { ".png", ".jpg", ".gif" }; 
     try 
     { 
      var di = new DirectoryInfo(path); 
      var rgFiles = di.GetFiles("*.*").Where(f => extensions.Contains(f.Extension.ToLower())); 
      Random R = new Random(); 
      file = rgFiles.ElementAt(R.Next(0,rgFiles.Count())).FullName; 
     } 
     // probably should only catch specific exceptions 
     // throwable by the above methods. 
     catch {} 
    } 
    return file; 
} 

我用這些路徑,但沒有工作的大概:

"/Images/defaultImages" 
"~/Images/defaultImages" 
"Images/defaultImages" 

什麼是正確的路徑?

+2

不要reacreate'Random',做一次:'私有靜態隨機R =新的隨機();' –

+0

你得到任何錯誤/異常? –

+0

不,但所有路徑都返回null。 – distance

回答

0

嘗試

Server.MapPath("~/Images/defaultImages") 

另外,還要確保您的defaultImages文件夾中包含的圖像文件

+0

命名空間'''MapPath「'不存在於命名空間'」Microsoft.SqlServer.Server「' – distance

+0

Server.MapPath屬於Page命名空間。嘗試'Page.Server.MapPath'或'HttpContext.Current.Server.MapPath' –

+1

@rezayegane:Server.MapPath中的'Server'是當你在頁面或控件中時可用的屬性。如果你的代碼不在web上下文中,你可以使用'HttpContext.Current.Server.MapPath'。如果您處於Web上下文中但名稱有衝突,則可以使用'this.Server.MapPath'來指定您使用該屬性,而不是'Microsoft.SqlServer.Server'類。 – Guffa