问题
I have uploaded a file(image) by asp.net. here is my code:
string imgpathpic =Convert .ToString (Session["imgpathpic"]);
long sizepic =Convert .ToInt64 (Session["sizepic"]);
string extpic = Convert.ToString(Session["extpic"]);
byte[] inputpic = new byte[sizepic - 1];
inputpic = FileUpload2.FileBytes;
for (int loop1 = 0; loop1 < sizepic; loop1++)
{
displayStringPic = displayStringPic + inputpic[loop1].ToString();
}
I converted byte[] to string by that for,but after line displayStringPic = displayStringPic + inputpic[loop1].ToString(); i receive this exception :
Index was outside the bounds of the array.
回答1:
The loop condition would be on the length of inputpic as you are accessing the element of inputpic in the loop body
for (int loop1 = 0; loop1 < inputpic.Length; loop1++)
{
displayStringPic = displayStringPic + inputpic[loop1].ToString();
}
You should use string builder instead of string for optimum solution when there a lot of string concatenation, see How to: Concatenate Multiple Strings (C# Programming Guide)
StringBuilder sb = new StringBuilder();
foreach(byte b in inputpic)
{
sb.Append(b.ToString());
}
string displayStringPic = sb.ToString();
You better convert the byte array to string using System.Text.Encoding
var str = System.Text.Encoding.UTF8.GetString(result);
Note Aside from converting the byte array to string, you can story the image as Image or in binary format.
来源:https://stackoverflow.com/questions/25112843/convert-byte-to-string-when-upload-a-file-in-asp-net