我不斷收到這個「索引超出數組邊界」的例外。我有一個帶有文件名的數據表。 webtable頁面上有一個鏈接到桌面的列表框。我試圖從列表框中選擇多個選項。然後將每個文件名發送到處理程序.ashx文件。你會看到我正在使用for循環。如何解決「索引超出數組範圍」異常?
這裏是main.aspx.cs代碼:
namespace MultiImagesImageHandler
{
public partial class Main : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
int[] AllselectedIndex = ListBox1.GetSelectedIndices();
int a = AllselectedIndex.Length;
DataView tempDV = SqlDataSource1.Select(DataSourceSelectArguments.Empty) as DataView;
for (int i = 0; i < a + 1; i++)
{
string fn = tempDV.Table.Rows[AllselectedIndex[i+1]].ItemArray[1].ToString();
ImgHandler.filename[i] = fn.Trim();
}
Response.Redirect("image1.htm");
}
}
}
的handler.ashx.cs代碼:
namespace MultiImagesImageHandler
{
/// <summary>
/// Summary description for ImgHandler
/// </summary>
public class ImgHandler : IHttpHandler
{
public static string[] filename = new string[16];
public void ProcessRequest(HttpContext context)
{
string saveTo = @"fileLocation" + filename[3];
FileStream writeStream1 = new FileStream(saveTo, FileMode.OpenOrCreate, FileAccess.ReadWrite);
string loadFrom = @"fileLocation" + filename[3];
using (FileStream fs1 = File.Open(loadFrom, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
ReadWriteStream(fs1, writeStream1);
}
byte[] tt = File.ReadAllBytes(context.Server.MapPath("~/images/" + filename[3]));
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(tt);
}
public bool IsReusable
{
get
{
return false;
}
}
// readStream is the stream you need to read
// writeStream is the stream you want to write to
private void ReadWriteStream(Stream readStream, Stream writeStream)
{
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, Length);
}
readStream.Close();
writeStream.Close();
}
}
}
我認爲這將填補陣列,使ImgHandler.ashx.cs從數據表中選擇的文件名,但它沒有。它不斷提出這個例外。我不知道爲什麼這不起作用。
for(int i = 0;我 user1274820 2014-11-03 21:33:49
改變這個'我 2014-11-03 21:34:16
你不應該在for循環中做一個+ 1,因爲你跳出界限 – Sybren 2014-11-03 21:34:43