上传asp.net文件时转换的byte []字符串 [英] convert byte[] to string when upload a file in asp.net

查看:147
本文介绍了上传asp.net文件时转换的byte []字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经上传用asp.net文件(影像)。
这里是我的code:

 字符串imgpathpic =转换的ToString(会话[imgpathpic]);
长sizepic =转换.ToInt64(会话[sizepic]);
字符串extpic = Convert.ToString(会话[extpic]);
字节[] = inputpic新的字节[sizepic - 1];
inputpic = FileUpload2.FileBytes;
对于(INT循环1 = 0;循环1< sizepic;循环1 ++)
{
    displayStringPic = displayStringPic + inputpic [循环1]的ToString();
}

我转换为字节[]字符串通过,但行后 displayStringPic = displayStringPic + inputpic [循环1]的ToString(); 我收到此异常:

指数数组的边界之外。


解决方案

循环条件将是对 inputpic 长度 $ C>为您正在访问inputpic的元素在循环体

 为(INT循环1 = 0;循环1< inputpic.Length;循环1 ++)
{
    displayStringPic = displayStringPic + inputpic [循环1]的ToString();
}

您应该使用字符串生成器,而不是字符串的最佳解决方案时出现了大量的字符串连接的,看的如何:串联多个字符串(C#编程指南)

  StringBuilder的SB =新的StringBuilder();
的foreach(在inputpic BYTE B)
{
    sb.Append(b.ToString());
}
字符串displayStringPic = sb.ToString();

您更好的使用字节数组转换为字符串 System.Text.Encoding

 无功海峡= System.Text.Encoding.UTF8.GetString(结果);

注意除了字节数组转换为字符串,可以故事图像作为图像或二进制格式。

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.

解决方案

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.

这篇关于上传asp.net文件时转换的byte []字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆