convert byte[] to string when upload a file in asp.net

帅比萌擦擦* 提交于 2019-12-04 05:23:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!