0
我有傳遞路徑(本地目錄)的C#處理程序文件。此路徑有時包含一個圖像,有時包含100個圖像。處理程序的目的是隨機選擇其中一個圖像,並將其返回到調用處理程序的slideshow.aspx文件。這是所有努力的過程,除了在某些情況下,我得到「500」錯誤和實例以下堆棧跟蹤只有一個圖像存在 - 有時,並非所有:從給定目錄中計數並隨機顯示圖像
[ArgumentException: Parameter is not valid.]
System.Drawing.Bitmap..ctor(String filename) +685715
SafetyMonitors.GetImage.ProcessRequest(HttpContext context) +213
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +913
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
這裏是我的處理代碼:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
namespace SafetyMonitors
{
/// <summary>
/// Grab images in shared public directory, based on incoming querystring path variable. randomize. stream new image back to request.
/// </summary>
public class GetImageUpdated : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var SharePath = context.Request["SharePath"];
Random rnd = new Random(); //randomize image
string[] images = Directory.GetFiles(@"E:\inetpub\wwwroot\service center monitors\Shares\" + SharePath, "*.*", SearchOption.TopDirectoryOnly);
if(images.Length == 1)
{
string imgToDisplay = images[images.Length];
Image img = new Bitmap(imgToDisplay);
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, ImageFormat.Png);
ms.WriteTo(context.Response.OutputStream);
}
}
else
{
string imgToDisplay = images[rnd.Next(images.Length - 1)];
Image img = new Bitmap(imgToDisplay);
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, ImageFormat.Png);
ms.WriteTo(context.Response.OutputStream);
}
}
context.Response.ContentType = "image/jpeg";
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
我已經嘗試在該IF語句中添加以處理目錄中只有一個圖像的情況,認爲它必須與計數和隨機()有關。
任何想法?謝謝!
奇怪,如果你只有一個像這樣的代碼應該給你的範圍異常的索引列。嘗試使用_string imgToDisplay = images [images.Length-1]; _如果你沒有任何圖像,你的if條件也不能正確處理。你確定該文件夾中只有圖像嗎? – Steve
試過了,結果也一樣。奇怪的是,如果我硬編碼字符串imgToDisplay = images [0];我仍然得到相同的結果... 50%的圖像時間,另一半'500'的錯誤。是的,只有一個圖像在該文件夾中。 – cardiac7