C# 上传文件(防止内存溢出)

7 篇文章 0 订阅

上传文件,之前使用WebClient的上传方法,UploadFile方法容易造成内存溢出,UploadData方法又一直没搞定,所以借鉴下网友的方法
文章主要内容源自(http://blogs.msdn.com/b/johan/archive/2006/11/15/are-you-getting-outofmemoryexceptions-when-uploading-large-files.aspx),本文做些修改,使其可直接使用:

public static string MyUploader(string strFileToUpload, string strUrl,Action<double,double> uploading)
{
   string strFileFormName = "file";
   Uri oUri = new Uri(strUrl);
   string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");

   // The trailing boundary string
   byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "--\r\n");
  //**注意此处的 strBoundary后的换行前加上--,不然会异常**
   // The post message header
   StringBuilder sb = new StringBuilder();
   sb.Append("--");
   sb.Append(strBoundary);
   sb.Append("\r\n");
   sb.Append("Content-Disposition: form-data; name=\"");
   sb.Append(strFileFormName);
   sb.Append("\"; filename=\"");
   sb.Append(Path.GetFileName(strFileToUpload));
   sb.Append("\"");
   sb.Append("\r\n");
   sb.Append("Content-Type: ");
   sb.Append("application/octet-stream");
   sb.Append("\r\n");
   sb.Append("\r\n");
   string strPostHeader = sb.ToString();
   byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);

   // The WebRequest
   HttpWebRequest oWebrequest = (HttpWebRequest)WebRequest.Create(oUri);
   oWebrequest.ContentType = "multipart/form-data; boundary=" + strBoundary;
   oWebrequest.Method = "POST";

   // This is important, otherwise the whole file will be read to memory anyway...
   oWebrequest.AllowWriteStreamBuffering = false;

   // Get a FileStream and set the final properties of the WebRequest
   FileStream oFileStream = new FileStream(strFileToUpload, FileMode.Open, FileAccess.Read);
   long length = postHeaderBytes.Length + oFileStream.Length + boundaryBytes.Length;
   oWebrequest.ContentLength = length;
   Stream oRequestStream = oWebrequest.GetRequestStream();

   // Write the post header
   oRequestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

   // Stream the file contents in small pieces (4096 bytes, max).
   byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)oFileStream.Length))];
   int bytesRead = 0;
   double size=0;
   while ((bytesRead = oFileStream.Read(buffer, 0, buffer.Length)) != 0)
      {
       oRequestStream.Write(buffer, 0, bytesRead);
       size+=bytesRead;
       if(uploading!=null)uploading(length ,size);
      }
    oFileStream.Close();

    // Add the trailing boundary
   oRequestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
   WebResponse oWResponse = oWebrequest.GetResponse();
   Stream s = oWResponse.GetResponseStream();
   StreamReader sr = new StreamReader(s);
   String sReturnString = sr.ReadToEnd();

    // Clean up
    oFileStream.Close();
    oRequestStream.Close();
    s.Close();
    sr.Close();

    return sReturnString;
}

如果有增加取消功能,可以调用oWebrequest的Abort方法取消上传请求。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中处理大文件下载时,可能会遇到内存溢出的问题。这是因为默认情况下,C#的文件下载操作会将整个文件加载到内存中。为了避免这个问题,可以使用一种流式处理的方法,只在需要的时候逐步读取文件内容,而不是一次性加载整个文件到内存中。 以下是一种处理大文件下载的方法: ```csharp public void DownloadFile(string url, string savePath) { using (var client = new WebClient()) { // 获取文件大小 long fileSize = Convert.ToInt64(client.Headers.Get("Content-Length")); using (var outputStream = new FileStream(savePath, FileMode.Create)) { using (var inputStream = client.OpenRead(url)) { byte[] buffer = new byte[4096]; int bytesRead; long totalBytesRead = 0; while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0) { outputStream.Write(buffer, 0, bytesRead); totalBytesRead += bytesRead; // 可以在此处添加进度更新代码 double progress = (double)totalBytesRead / fileSize; Console.WriteLine($"Download progress: {progress:P}"); } } } } } ``` 这段代码使用`WebClient`来下载文件,并通过`OpenRead`方法以流的形式读取文件内容,然后使用`FileStream`以流的方式写入到保存路径的文件中。通过循环逐步读取文件内容,并可以在每次读取时更新下载进度。 这种流式处理的方法可以有效避免因为大文件导致的内存溢出问题。同时,你也可以根据需要添加进度更新的代码,以便在下载过程中显示下载进度。 希望这个方法能够帮助到你解决内存溢出的问题!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值