【问题标题】:Problem Uploading a file via FTP using FtpWebRequest when the file does not already exist on FTP server当文件在 FTP 服务器上不存在时,使用 FtpWebRequest 通过 FTP 上传文件时出现问题
【发布时间】:2011-08-25 01:55:00
【问题描述】:

这似乎是一个微不足道的问题,但我在网络上搜索答案(甚至在这个网站上)迫使我明确提出这个问题。

我正在通过 FTP 将文件从我的服务器上传到远程服务器。我的代码看起来像这样...

public void Upload(string fileToUpload)
    {
        // Get the object used to communicate with the server.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.remoteserver.com/Data/" + fileToUpload);
        request.UsePassive = false;
        request.UseBinary = true;
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.Credentials = new NetworkCredential ("username","password");

        // Copy the contents of the file to the request stream.
        StreamReader sourceStream = new StreamReader(fileToUpload);
        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();

        Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

        response.Close();
    }

这一切看起来都非常简单。我遇到的问题是当远程服务器上不存在该文件时出现 550 错误。我假设如果该文件不存在,那么该文件将被创建。此外,我假设如果这样做,它将被覆盖。

由于情况并非如此(至少在编写新文件时),我会进一步假设我应该(a)首先以某种方式检查文件,并且(b)如果它不存在则创建它。但是如何做到这一点呢?

谢谢,

迈克

【问题讨论】:

  • 您是否检查过该帐户有权在 FTP 服务器上创建文件?
  • 你在fileToUpload 中传递什么,一个绝对文件路径,如c:\File.txt 或只是一个文件名,如File.txt?另外,您知道您的程序只适用于文本文件,对吗?
  • @JNappi:这不是权限问题,因为 FTP 凭据适用于具有写入权限的用户(我控制了两台服务器,因此可以确认这一点)。
  • @Chris Haas:我正在传递“File.txt”,我知道这仅适用于文本文件。
  • @Chris Haas:啊!我刚刚检查了一下,fileToUpload 是本地文件的完整路径!很好的收获(我真是个白痴!)。您可以添加一个“答案”以便我给您评分吗?

标签: c# .net ftp ftpwebrequest


【解决方案1】:

(评论转换为答案)

您将什么传递到fileToUpload,一个绝对文件路径,如c:\File.txt,或者只是一个文件名,如File.txt?另外,您知道您的程序仅适用于文本文件,对吗?

【讨论】:

  • 谢谢...不敢相信我来这里是为了调试一个参数:)...但还是非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 2020-09-12
相关资源
最近更新 更多