您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

了解C#文件上传类,文件流,字节数组等知识

2025/10/23 20:39:33发布17次查看
using system; using system.io; using system.web; using system.web.ui.webcontrols; namespace dotnet.utilities { /// <summary> /// 文件上传类 /// </summary> public class fileup { public fileup() { } /// <summary> /// 转换为字节数组 /// </summary> /// <param name="filename">文件名</param> /// <returns>字节数组</returns> public byte[] getbinaryfile(string filename) { if (file.exists(filename)) { filestream fsm = null; try { fsm = file.openread(filename); return this.convertstreamtobytebuffer(fsm); } catch { return new byte[0]; } finally { fsm.close(); } } else { return new byte[0]; } } /// <summary> /// 流转化为字节数组 /// </summary> /// <param name="thestream">流</param> /// <returns>字节数组</returns> public byte[] convertstreamtobytebuffer(system.io.stream thestream) { int bi; memorystream tempstream = new system.io.memorystream(); try { while ((bi = thestream.readbyte()) != -1) { tempstream.writebyte(((byte)bi)); } return tempstream.toarray(); } catch { return new byte[0]; } finally { tempstream.close(); } } /// <summary> /// 上传文件 /// </summary> /// <param name="posphotoupload">控件</param> /// <param name="savefilename">保存的文件名</param> /// <param name="imagepath">保存的文件路径</param> public string filesc(fileupload posphotoupload, string savefilename, string imagepath) { string state = ""; if (posphotoupload.hasfile) { if (posphotoupload.postedfile.contentlength / 1024 < 10240) { string mimetype = posphotoupload.postedfile.contenttype; if (string.equals(mimetype, "image/gif") || string.equals(mimetype, "image/pjpeg")) { string extfilestring = system.io.path.getextension(posphotoupload.postedfile.filename); posphotoupload.postedfile.saveas(httpcontext.current.server.mappath(imagepath)); } else { state = "上传文件类型不正确"; } } else { state = "上传文件不能大于10m"; } } else { state = "没有上传文件"; } return state; } /// <summary> /// 上传文件 /// </summary> /// <param name="bindata">字节数组</param> /// <param name="filename">文件名</param> /// <param name="filetype">文件类型</param> //-------------------调用---------------------- //byte[] by = getbinaryfile("e:\\hello.txt"); //this.savefile(by,"hello",".txt"); //--------------------------------------------- public void savefile(byte[] bindata, string filename, string filetype) { filestream filestream = null; memorystream m = new memorystream(bindata); try { string savepath = httpcontext.current.server.mappath("~/file/"); if (!directory.exists(savepath)) { directory.createdirectory(savepath); } string file = savepath + filename + filetype; filestream = new filestream(file, filemode.create); m.writeto(filestream); } finally { m.close(); filestream.close(); } } } }
以上就是了解c#文件上传类,文件流,字节数组等知识的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product