简体   繁体   中英

Ftp uploaded files are corrupted unless “txt” files c#

I'm using an FTP server in c# and I have to upload files of different typer (.png, .xlsx, docx....), at the moment the upload is done for every file type, but if I try to open a file (except for .txt) it says that the file is corrupted. what am I doing wrong?

thank you

    FtpWebResponse response = null;
    try
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
        if (request == null)
        {
            result.SetError(Translate.InvalidUrl, url);
            return false;
        }
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.UseBinary = true;

        request.Credentials = new NetworkCredential(username, password);

        if (sourceStream == null)
        {
            result.SetError(Translate.FileErrorReading);
            return false;
        }
        byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        sourceStream.Close();

        request.ContentLength = fileContents.Length;

        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();

        response = (FtpWebResponse)request.GetResponse();

        result.SetInformation(Translate.FileSuccefullUpload, filename);

    }
    catch (Exception e)
    {
        result.SetError(e.Message);
        return false;
    }
    finally
    {
        if (response != null)
            response.Close();
    }
    return result.Successful;
    }

Why are you using Encoding.UTF8.GetBytes ?

This trim bytes.

You should read your data in binary mode (ie File.ReadAllBytes ).

检查您使用的是ASCII还是BINARY传输模式。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM