處理大文件時,可以使用C#中的流式處理來避免將整個文件加載到內存中。以下是一個示例代碼,演示如何處理大文件的form-data:
using System;
using System.IO;
using System.Net;
using System.Text;
class Program
{
static void Main()
{
string url = "http://example.com/upload";
string filePath = "path/to/largefile.txt";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=---------------------------12345";
using (var requestStream = request.GetRequestStream())
{
using (var fileStream = File.OpenRead(filePath))
{
byte[] boundaryBytes = Encoding.ASCII.GetBytes("-----------------------------12345\r\n");
byte[] headerBytes = Encoding.ASCII.GetBytes($"Content-Disposition: form-data; name=\"file\"; filename=\"{Path.GetFileName(filePath)}\"\r\nContent-Type: application/octet-stream\r\n\r\n");
byte[] footerBytes = Encoding.ASCII.GetBytes("\r\n-----------------------------12345--\r\n");
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
requestStream.Write(headerBytes, 0, headerBytes.Length);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
requestStream.Write(footerBytes, 0, footerBytes.Length);
}
}
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream receiveStream = response.GetResponseStream())
{
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
Console.WriteLine(readStream.ReadToEnd());
}
}
catch (WebException ex)
{
Console.WriteLine("Error uploading file: " + ex.Message);
}
}
}
上面的代碼中,我們使用File.OpenRead()
方法打開要上傳的大文件,并使用流式處理的方式逐塊將文件內容寫入HttpWebRequest
的請求流中。這樣可以避免將整個文件加載到內存中,從而有效處理大文件的form-data。