ftp上传文件在c#中损坏

时间:2018-01-26 11:08:01

标签: c# asp.net ftp

你好我有这个代码通过c#使用ftp上传图像或word文件。

代码工作正常它将文件上传到ftp但上传后文件损坏请告知此问题是什么错误

    //FTP Server URL.
    string ftp = "ftp://ftpip/";

    //FTP Folder name. Leave blank if you want to upload to root folder.
    string ftpFolder = "folder path to upload";

    byte[] fileBytes = null;

    //Read the FileName and convert it to Byte array.
    string fileName = Path.GetFileName(FileUpload1.FileName);
    using (StreamReader fileStream = new StreamReader(FileUpload1.PostedFile.InputStream))
    {
        fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
        fileStream.Close();
    }

    try
    {
        //Create FTP Request.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + fileName);
        request.Method = WebRequestMethods.Ftp.UploadFile;

        //Enter FTP Server credentials.
        request.Credentials = new NetworkCredential("ftpuser", "ftppassowrd");
        request.ContentLength = fileBytes.Length;
        request.UsePassive = true;
        request.UseBinary = true;
        request.ServicePoint.ConnectionLimit = fileBytes.Length;
        request.EnableSsl = false;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(fileBytes, 0, fileBytes.Length);
            requestStream.Close();
        }

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        lblMessage.Text += fileName + " uploaded.<br />";
        response.Close();
    }
    catch (WebException ex)
    {
        throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
    }

1 个答案:

答案 0 :(得分:4)

您可以使用BinaryReader而不是将字节作为UTF8编码。你应该改变它;

using (StreamReader fileStream = new StreamReader(FileUpload1.PostedFile.InputStream))
{
    fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
    fileStream.Close();
}

FileUpload1.PostedFile.InputStream.Seek(0, SeekOrigin.Begin);
using (var binaryReader = new BinaryReader(FileUpload1.PostedFile.InputStream))
{
    fileBytes = binaryReader.ReadBytes(FileUpload1.PostedFile.ContentLength);
}