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

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x