【问题标题】:C# How to use FTP upload File ClassC#如何使用FTP上传文件类
【发布时间】:2020-07-12 20:09:57
【问题描述】:

提前抱歉这个愚蠢的问题。我有一些关于在 C# 上使用 FTP 上传文件的问题,我需要指导:

 public void UploadFile(string FullPathFilename)
 {
    string filename = Path.GetFileName(FullPathFilename);

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + filename);
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(_remoteUser, _remotePass);

    StreamReader sourceStream = new StreamReader(FullPathFilename);
    byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());

    request.ContentLength = fileContents.Length;

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

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

    response.Close();
    requestStream.Close();
    sourceStream.Close();
 }

所以,我不需要创建新文件夹,我应该用什么替换 [FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + filename);] ?这是在远程 ftp 站点中创建一个文件夹吗? 我在 FTP 类中使用此代码,并且我已经创建并填充了文件。如何在我的 Program.cs 中调用它来将文件上传到 FTP 目录?

【问题讨论】:

  • WebRequest.Create(_remoteHost + filename) 不创建新文件夹。它创建WebRequest 类实例,其参数设置为_remoteHost + filename 值。这是服务器上实际要上传的文件名。你应该像UploadFile(file2upload) 这样称呼它,其中file2upload 是带有要上传的文件名的字符串参数(如c:\temp\filetoupload.txt

标签: c# ftp upload


【解决方案1】:

网址格式如下:

WebRequest.Create("ftp://ftp.example.com/path/to/directory/filename.ext");

【讨论】:

    猜你喜欢
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2014-09-11
    • 1970-01-01
    • 2012-09-12
    相关资源
    最近更新 更多