如何使用C#将excel文件发送到FTP?

时间:2013-11-22 02:51:16

标签: c# ftp c#-2.0

我使用以下代码将excel文件发送到FTP。文件正在发送,文件大小也一样。但文件只包含空格。

ftpAddress = "X.X.X.X";
            outFilePath = "MyFolder/Sample.xls";
            inFilePath = "D:/Hello.xls";
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + ftpAddress + "/" + outFilePath);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.UseBinary = true;
            request.UsePassive = true;
            request.KeepAlive = true;
            request.Credentials = new NetworkCredential(userId, password);
            //FileStream stream = File.OpenRead(inFilePath);
            byte[] fileContents = File.ReadAllBytes(inFilePath);
            //byte[] buffer = new byte[stream.Length];
            request.ContentLength = fileContents.Length;

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

            //Shows confirm message
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Console.WriteLine(response);
            response.Close();

请帮忙。提前谢谢。

1 个答案:

答案 0 :(得分:0)

来源:http://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx

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();
        }
    }
}

}