webclient.底层连接已关闭:接收端出现意外错误
本文关键字:接收端 意外 错误 连接 webclient | 更新日期: 2023-09-27 18:12:02
我正在尝试使用下面的代码上传图像和视频,使用ftp上传图像没有问题,但是当我上传视频时,我得到以下错误
误差The underlying connection was closed: An unexpected error occurred on a receive.
下面是我用来上传
的代码 try
{
string uploadFileName = Path.GetFileName(FU_Video.FileName);
uploadFileName = "video." + uploadFileName.Split('.')[1];
using (WebClient client = new WebClient())
{
string ftpAddres = "ftp://username:pasword@url-path" + fullname;
if (!GetAllFilesList(ftpAddres, "username", "password"))
{
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpAddres);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
ftp.KeepAlive = false;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
}
client.UploadData(new Uri(ftpAddres + "/" + uploadFileName), FU_Video.FileBytes);
}
,这是堆栈跟踪。
堆栈跟踪
at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request)
at System.Net.WebClient.UploadData(Uri address, String method, Byte[] data)
at System.Net.WebClient.UploadData(Uri address, Byte[] data)
at MentorMentee.SignUp.signup.btn_VidPreview_Click(Object sender, EventArgs e) in I:'VS Projects'code'MentorMentee1'MentorMentee'SignUp'signup.aspx.cs:line 469
搜索后,我读到使连接存活错误,但我在client.UploadData(uri,byte[]);
上得到错误
请让我知道我的代码有什么问题?当视频上传到ftp,但我得到错误。
我记得有类似的问题,但不记得确切是什么使它工作。下面的代码很适合我:
public void Upload(Stream stream, string fileName)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
try
{
FtpWebRequest ftpRequest = CreateFtpRequest(fileName);
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
using (Stream requestSream = ftpRequest.GetRequestStream())
{
Pump(stream, requestSream);
}
var ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
ftpResponse.Close();
}
catch (Exception e)
{
throw new FtpException(
string.Format("Failed to upload object. fileName: {0}, stream: {1}", fileName, stream), e);
}
}
private FtpWebRequest CreateFtpRequest(string fileName)
{
if (fileName == null)
{
throw new ArgumentNullException("fileName");
}
string serverUri = string.Format("{0}{1}", ftpRoot, fileName);
var ftpRequest = (FtpWebRequest)WebRequest.Create(serverUri);
ftpRequest.Credentials = new NetworkCredential(configuration.UserName, configuration.Password);
ftpRequest.UsePassive = true;
ftpRequest.UseBinary = true;
ftpRequest.KeepAlive = false;
return ftpRequest;
}
private static void Pump(Stream input, Stream output)
{
var buffer = new byte[2048];
while (true)
{
int bytesRead = input.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
break;
}
output.Write(buffer, 0, bytesRead);
}
}