如何使用c#.net将许多文本文件从本地计算机上传到ftp

本文关键字:计算机 ftp 文件 何使用 net 文本 许多 | 更新日期: 2023-09-27 18:23:51

我需要使用c#将文本文件从本地机器上传到ftp服务器。我试过遵循代码,但没有成功。

private bool UploadFile(FileInfo fileInfo) 
{
    FtpWebRequest request = null;
    try
    {
        string ftpPath = "ftp://www.tt.com/" + fileInfo.Name
        request = (FtpWebRequest)WebRequest.Create(ftpPath);
        request.Credentials = new NetworkCredential("ftptest", "ftptest"); 
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.KeepAlive = false;
        request.Timeout = 60000; // 1 minute time out
        request.ServicePoint.ConnectionLimit = 15;
        byte[] buffer = new byte[1024];
        using (FileStream fs = new FileStream(fileInfo.FullPath, FileMode.Open))
        {
            int dataLength = (int)fs.Length;
            int bytesRead = 0;
            int bytesDownloaded = 0;
            using (Stream requestStream = request.GetRequestStream())
            {
                while (bytesRead < dataLength)
                {
                    bytesDownloaded = fs.Read(buffer, 0, buffer.Length);
                    bytesRead = bytesRead + bytesDownloaded;
                    requestStream.Write(buffer, 0, bytesDownloaded);
                }
                requestStream.Close();
            }
        }
        return true;
    }
    catch (Exception ex)
    {
        throw ex;                
    }
    finally
    {
        request = null;
    }
    return false;
}// UploadFile

有什么建议吗???

如何使用c#.net将许多文本文件从本地计算机上传到ftp

您需要通过调用GetResponse()来实际发送请求。

您还可以通过调用fs.CopyTo(requestStream)来简化代码。

我修改了一些ftp代码,得到了以下代码,这似乎对我来说很有效。

ftpUploadloc是ftp://ftp.yourftpsite.com/uploaddir/yourfilename.txt

ftpUsernameftpPassword应该是不言自明的。

最后,currentLog是您正在上传的文件的位置。

让我知道这对你来说是如何实现的,如果其他人有任何其他建议,我欢迎。

    private void ftplogdump()
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUploadloc);
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
        StreamReader sourceStream = new StreamReader(currentLog);
        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();

        // Remove before publishing
        Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
        response.Close();
    }