【发布时间】:2014-11-03 21:32:53
【问题描述】:
我不断收到此“索引超出数组范围”异常。我有一个带有文件名的数据表。连接到平板电脑的网页表单页面上有一个列表框。我正在尝试从列表框中选择多个选项。然后将每个文件名发送到处理程序 .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; i
-
将此
i < a + 1更改为i < a并学习使用调试器 -
当你越界时,你不应该在你的 for 循环中做 a+1
-
异常信息的哪一部分你不明白?
-
您的代码中有另一个错误
tempDV.Table.Rows[AllselectedIndex[i+1]]似乎您从数据表中选择了错误的行。如果您的用户从您的 ListBox1 中选择最后一项,您认为会发生什么?