0

I have the following code to perform FTP file:

    private bool InitFTPTransfer(string filePath)
    {
        Uri ipAddress = new Uri(ddcdao.ddcAddress);

        string ftpAddress = "ftp://10.175.95.11/mnt/flash" +Path.GetFileName(filePath);
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpAddress);
        request.Method = WebRequestMethods.Ftp.UploadFile;

        request.Credentials = new NetworkCredential(Properties.Settings.Default.SysFTPID, Properties.Settings.Default.SysFTPPassword);


        byte[] fileContents = File.ReadAllBytes(filePath);

        request.ContentLength = fileContents.Length;

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

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

        response.Close();
        return true;
    }

The file transfers without a problem but the file is placed on the root, not at the designated directory (/mnt/flash).

I was under the impression that specifying a directory in ftp address should set the destination properly but this may not be true for embedded linux.

How can I fix this issue?

TtT23
  • 6,876
  • 34
  • 103
  • 174

1 Answers1

1

The path appears to be correct. However:

  1. URL encode the file name first to escape any invalid characters.
  2. The code is missing a slash (/) between the folder and the file name. This may cause the path to be invalid, causing it to write to the root folder.
  3. Use using or try...finally blocks to close the various streams in case an exception is thrown.
  4. Use stream.CopyTo (see How do I copy the contents of one stream to another?) instead of reading the whole file in. This may have issues if the files are particularly large.

The problem is likely on the FTP server configuration side. The FTP server appears to be serving up the root folder of the file system as its root folder which is a bad practice. The FTP server should only serve up the folders files should be downloaded from or uploaded to. However, this may be a feature of the configuration on the embedded Linux you are using.

Community
  • 1
  • 1
akton
  • 14,148
  • 3
  • 43
  • 47