• C#上传任何格式类型的文件到FTP Server的实现方式
  • 发布于 2个月前
  • 249 热度
    0 评论
  • 张乐乐
  • 1 粉丝 22 篇博客
  •   

微软在MSDN上有提供一个C#上传文件到FTP服务器的实现方式,实现代码如下:


using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
            
            // Copy the contents of the file to the request stream.
            StreamReader sourceStream = new StreamReader("testfile.txt");
            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();
            }
        }
    }
}

这个例子是使用Streamreader对象从文本文件中读取字符串,然后将字符串转换为字节并实现上载。这种方式只适用于上传文本文件,如果要上传二进制的文件,比如图片,则会报错,那该怎么解决上传二进制文件报错的问题呢?如下三种方法可以试试。

1.调用file.readallbytes读取字节,并写入请求流:

byte[] fileContents = File.ReadAllBytes(filePath);
using (Stream requestStream = request.GetRequestStream())
{
    requestStream.Write(fileContents, 0, fileContents.Length);
}
2.使用file stream读取文件,并将文件流复制到请求流:

public static async Task<FtpStatusCode> FtpUploadAsync(string uri, string userName, string password, string filePath)
{
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(userName, password);
    // request.UsePassive is true by default.

    using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
    using (Stream requestStream = request.GetRequestStream())
    {
        await fileStream.CopyToAsync(requestStream);
    }

    using (FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync())
    {
        return response.StatusCode;
    }
}
3.直接使用WebClient对象

public static async Task FtpUploadAsync(string uri, string userName, string password, string filePath)
{
    using (WebClient webClient = new WebClient())
    {
        webClient.Credentials = new NetworkCredential(userName, password);
        await webClient.UploadFileTaskAsync(uri, WebRequestMethods.Ftp.UploadFile, filePath);
    }
}


用户评论