开发者

How Upload File To Buffer in ASP.NET

开发者 https://www.devze.com 2023-02-08 07:55 出处:网络
I\'m trying to upload a file. However, much of the material I find on the Internet explains how to save the file to a folder on the server, but for my solution I just needed to buffer. Is it possible?

I'm trying to upload a file. However, much of the material I find on the Internet explains how to save the file to a folder on the server, but for my solution I just needed to buffer. Is it possible? I upload the file to the server buffer, then read and cle开发者_运维问答an.

Obs.: I am using telerik components, and need to read / import an Excel file.

Thanks


So if you use a binary stream, the approach to buffer it regardless of the context of execution (asp.net vs winforms or whatever) is pretty common:

public static byte[] ReadFile(string filePath)
{
  byte[] buffer;
  FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  try
  {
     int length = (int)fileStream.Length;  // get file length
     buffer = new byte[length];            // create buffer
     int count;                            // actual number of bytes read
     int sum = 0;                          // total number of bytes read

    // read until Read method returns 0 (end of the stream has been reached)
    while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
       sum += count;  // sum is a buffer offset for next reading
    }
  finally
  {
    fileStream.Close();
  }
   return buffer;
 }

Also, check out this:

http://www.yoda.arachsys.com/csharp/readbinary.html


The default FileUpload component presents you the file as a Byte[] - you could just wrap it in a MemoryStream:

var strm = new MemoryStream(fileUpload.PostedFile.Contents);
  // I think its PostedFile.Contents, something like that anyway
0

精彩评论

暂无评论...
验证码 换一张
取 消