gpt4 book ai didi

c# - 如何在c#中快速上传文件到服务器

转载 作者:太空宇宙 更新时间:2023-11-03 20:18:45 25 4
gpt4 key购买 nike

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("request_uri_string");
FileStream fileStream = new FileStream("path_to_my_file", FileMode.Open, FileAccess.Read);
Stream requestStream = request.GetRequestStream();
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
int bytesRead = 1;
while (bytesRead != 0)
{
bytesRead = fileStream.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
}
request.Close();
fileStream .Close();

目前我正在使用上面的代码。

还有比这更好(意味着快速)的其他方法吗?

最佳答案

不确定这是否更快,但可读性更高:

using (var webClient = new WebClient())
{
webClient.DownloadFile(remoteFileUrl, localFileName);
}

编辑:

因为 WebClientIDisposable,所以应该正确处理它(我添加了 using)。

MSDN 说:

This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.

关于c# - 如何在c#中快速上传文件到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15004203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com