远程服务器返回错误:(553)不允许使用文件名[C#] [FTP]

时间:2019-04-22 17:52:32

标签: c# ftp

我正在编写一个程序,用于将文件从USB复制到FTP服务器,这是代码的一部分:

        private const string ftp_url = @"ftp://an_ip_addrs/X";

        private static void Upload(string sourceDir)
        {
            using (WebClient client = new WebClient())
            {
                try
                {
                    client.Credentials = new NetworkCredential(ftp_username, ftp_psw);

                    foreach (var filename in Directory.GetFiles(sourceDir))
                    {
                        Console.WriteLine("Preparing to upload --> " + filename);

                        client.UploadFile(ftp_url, WebRequestMethods.Ftp.UploadFile, filename);
                        Console.WriteLine("File Uploaded!");
                    }
                } catch (Exception e)
                {
                    Console.WriteLine("Err FTP --> " + e);
                }
            }
        }

这是Preparing to upload的输出:

Preparing to upload --> C:\Users\aimproxy\jn54comu\FASM - Copy (10).PDF

实际上,我从try catch block得到了这个错误:

"Err FTP -->  System.Net.WebException: The remote server returned an error: (553) File name not allowed.
   at System.Net.WebClient.UploadFile(Uri address, String method, String fileName)
   at System.Net.WebClient.UploadFile(String address, String method, String fileName)
   at usb_backdoor_csharp.Program.Upload(String sourceDir) in C:\Users\aimproxy\Desktop\Program.cs:line 29

根据要求,这是ftp.exe的输出

Connected to 192.168.1.5.
220 Welcome to virtual FTP service.
503 USER expected.
User (192.168.1.5:(none)): upload
331 Password please.
230 User logged in.
ftp> dir
200 PORT 192.168.1.67:59392 OK
150 BINARY data connection established.
drwxrwxrwx   2 0        0        4096 Apr 22 18:07 X
226 Directory list has been submitted.
ftp: 135 bytes received in 0.02Seconds 7.50Kbytes/sec.

1 个答案:

答案 0 :(得分:1)

问题是WebClient UploadFile需要一个完整的目标文件路径,即包括目标文件名。您正在传递目标文件夹,并期望它重新使用源文件名-这是明智的,我很奇怪,它无法正常工作。当然,文档IMO中并未明确说明。

正如评论中所讨论的,这对您有效:

client.UploadFile(Path.Combine(ftp_url, Path.GetFileName(filename)), filename);

我更喜欢URL组合功能,而不是Path组合功能,例如from this old question-类似于:

client.UploadFile(new Uri(new Uri(ftp_url), Path.GetFileName(filename)), filename);