简体   繁体   中英

FTP upload doesn't upload content of CSV files

I'm working on a project that uploads .CSV files to a FTP server. The program creates files successfully to a path on my computer, where the files have content, when I open them in Excel.

The program succeeds uploading the files to the server, and I can see the files on the server.

The problem is, that the .CSV files doesn't have any content and fills 0 byte, when I open them from the server.

Does anyone know, what I have done wrong?

Thanks in advance!

Here is the code, that I use to upload to the server:

        private void sendFileBTN_Click(object sender, EventArgs e)
    {
        Upload("ftp://FTPServerName", "FTPBrugernavn", "FTPpassword", path + @"\fileNameToUpload.csv");
    }

public void Upload(string ftpServer, string username, string password, string filename)
    {
        var Settingsdict = File.ReadAllLines(".\\" + "Settings" + ".csv").Select(l => l.Split(';').ToArray()).ToArray();
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + "/" + Settingsdict[4][1] +
        Path.GetFileName(filename));
        request.Method = WebRequestMethods.Ftp.UploadFile;

        request.Credentials = new NetworkCredential(username, password);
        request.UsePassive = true;
        request.UseBinary = false;
        request.KeepAlive = true;

        StreamReader sourceStream = new StreamReader("testfile.txt");
        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();

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        FileStream stream = File.OpenRead(filename);
        byte[] buffer = new byte[stream.Length];
        stream.Read(buffer, 0, buffer.Length);
        stream.Close();
        response.Close();
    }

I found out. Here is the code I have to use instead:

using (WebClient client = new WebClient())
            {
                client.Credentials = new NetworkCredential(username, password);
                client.UploadFile(ftpServer + "/" + Path.GetFileName(filepathAndName), filepathAndName);
            }

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