C# winform上传文件
时间: 2023-12-10 15:04:07 浏览: 231
winform上传文件
4星 · 用户满意度95%
以下是C# WinForm上传文件的示例代码:
```csharp
private void btnUpload_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog.FileName;
string url = "http://localhost/UploadFileWeb/WebForm1.aspx";
string paramName = "file";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
request.ContentType = "multipart/form-data; boundary=" + boundary;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
string header = string.Format(headerTemplate, paramName, Path.GetFileName(filePath));
byte[] headerBytes = Encoding.UTF8.GetBytes(header);
requestStream.Write(headerBytes, 0, headerBytes.Length);
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
}
byte[] trailerBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
requestStream.Write(trailerBytes, 0, trailerBytes.Length);
}
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string responseText = reader.ReadToEnd();
MessageBox.Show(responseText);
}
}
}
}
```
该示例代码使用HttpWebRequest类向指定的URL上传文件。在上传文件之前,需要设置请求的Method为POST,ContentType为multipart/form-data,并设置请求头部的边界(boundary)。然后,将文件内容写入请求流中,最后发送请求并获取响应。在获取响应后,可以从响应流中读取服务器返回的内容。
阅读全文