2

hello i have this code to upload image or word file through c# by using ftp.

the code works fine it uploads the file to ftp but file goes corrupted after uploading please advice what is wrong in this thanks

    //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);
    }
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
user3597236
  • 115
  • 2
  • 12

1 Answers1

5

You could use BinaryReader instead of getting the bytes as UTF8 encoding. You should change it;

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

to

FileUpload1.PostedFile.InputStream.Seek(0, SeekOrigin.Begin);
using (var binaryReader = new BinaryReader(FileUpload1.PostedFile.InputStream))
{
    fileBytes = binaryReader.ReadBytes(FileUpload1.PostedFile.ContentLength);
}
lucky
  • 12,734
  • 4
  • 24
  • 46