远程服务器返回错误: (553) File name not allowed [C#] [FTP]

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (390)

我正在编写一个程序将文件从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 到 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.
提问于
用户回答回答于

问题是WebClient UploadFile需要一个完整的目标文件路径,即包括目标文件名。你正在传递目标文件夹,并期望它重用源文件名 - 这是明智的,我很惊讶不起作用。它当然没有在IMO文档中明确说明。

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

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

我更喜欢URL组合功能,而不是路径组合功能,例子来自这个老问题 - 类似于:

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

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励