【问题标题】:Incomplete upload ftp in c#c#中不完整的上传ftp
【发布时间】:2013-02-07 21:38:39
【问题描述】:

我想从我的 C# 应用程序中运行 ftp,但是他在发送时喝了一个问题,我无法理解。

当我运行上传脚本时,它与服务器连接良好,但会创建一个空文件。

你能帮帮我吗?

我用这个类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace FTPClasse
{
   class ftp
{
private string host = null;
private string user = null;
private string pass = null;
private FtpWebRequest ftpRequest = null;
private FtpWebResponse ftpResponse = null;
private Stream ftpStream = null;
private int bufferSize = 2048;

/* Construct Object */
public ftp(string hostIP, string userName, string password) { host = hostIP; user = userName; pass = password; }

/* Download File */
public void download(string remoteFile, string localFile)
{
    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
        /* Establish Return Communication with the FTP Server */
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        /* Get the FTP Server's Response Stream */
        ftpStream = ftpResponse.GetResponseStream();
        /* Open a File Stream to Write the Downloaded File */
        FileStream localFileStream = new FileStream(localFile, FileMode.Create);
        /* Buffer for the Downloaded Data */
        byte[] byteBuffer = new byte[bufferSize];
        int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
        /* Download the File by Writing the Buffered Data Until the Transfer is Complete */
        try
        {
            while (bytesRead > 0)
            {
                localFileStream.Write(byteBuffer, 0, bytesRead);
                bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
            }
        }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
        /* Resource Cleanup */
        localFileStream.Close();
        ftpStream.Close();
        ftpResponse.Close();
        ftpRequest = null;
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    return;
}

/* Upload File */
public void upload(string remoteFile, string localFile)
{
    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
        /* Establish Return Communication with the FTP Server */
        ftpStream = ftpRequest.GetRequestStream();
        /* Open a File Stream to Read the File for Upload */
        FileStream localFileStream = new FileStream(localFile, FileMode.Create);
        /* Buffer for the Downloaded Data */
        byte[] byteBuffer = new byte[bufferSize];
        int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
        /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
        try
        {
            while (bytesSent != 0)
            {
                ftpStream.Write(byteBuffer, 0, bytesSent);
                bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
            }
        }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
        /* Resource Cleanup */
        localFileStream.Close();
        ftpStream.Close();
        ftpRequest = null;
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    return;
}

/* Delete File */
public void delete(string deleteFile)
{
    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + deleteFile);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
        /* Establish Return Communication with the FTP Server */
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        /* Resource Cleanup */
        ftpResponse.Close();
        ftpRequest = null;
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    return;
}

/* Rename File */
public void rename(string currentFileNameAndPath, string newFileName)
{
    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + currentFileNameAndPath);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.Rename;
        /* Rename the File */
        ftpRequest.RenameTo = newFileName;
        /* Establish Return Communication with the FTP Server */
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        /* Resource Cleanup */
        ftpResponse.Close();
        ftpRequest = null;
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    return;
}

/* Create a New Directory on the FTP Server */
public void createDirectory(string newDirectory)
{
    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + newDirectory);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
        /* Establish Return Communication with the FTP Server */
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        /* Resource Cleanup */
        ftpResponse.Close();
        ftpRequest = null;
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    return;
}

/* Get the Date/Time a File was Created */
public string getFileCreatedDateTime(string fileName)
{
    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + fileName);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp;
        /* Establish Return Communication with the FTP Server */
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        /* Establish Return Communication with the FTP Server */
        ftpStream = ftpResponse.GetResponseStream();
        /* Get the FTP Server's Response Stream */
        StreamReader ftpReader = new StreamReader(ftpStream);
        /* Store the Raw Response */
        string fileInfo = null;
        /* Read the Full Response Stream */
        try { fileInfo = ftpReader.ReadToEnd(); }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
        /* Resource Cleanup */
        ftpReader.Close();
        ftpStream.Close();
        ftpResponse.Close();
        ftpRequest = null;
        /* Return File Created Date Time */
        return fileInfo;
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    /* Return an Empty string Array if an Exception Occurs */
    return "";
}

/* Get the Size of a File */
public string getFileSize(string fileName)
{
    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + fileName);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
        /* Establish Return Communication with the FTP Server */
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        /* Establish Return Communication with the FTP Server */
        ftpStream = ftpResponse.GetResponseStream();
        /* Get the FTP Server's Response Stream */
        StreamReader ftpReader = new StreamReader(ftpStream);
        /* Store the Raw Response */
        string fileInfo = null;
        /* Read the Full Response Stream */
        try { while (ftpReader.Peek() != -1) { fileInfo = ftpReader.ReadToEnd(); } }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
        /* Resource Cleanup */
        ftpReader.Close();
        ftpStream.Close();
        ftpResponse.Close();
        ftpRequest = null;
        /* Return File Size */
        return fileInfo;
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    /* Return an Empty string Array if an Exception Occurs */
    return "";
}

/* List Directory Contents File/Folder Name Only */
public string[] directoryListSimple(string directory)
{
    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
        /* Establish Return Communication with the FTP Server */
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        /* Establish Return Communication with the FTP Server */
        ftpStream = ftpResponse.GetResponseStream();
        /* Get the FTP Server's Response Stream */
        StreamReader ftpReader = new StreamReader(ftpStream);
        /* Store the Raw Response */
        string directoryRaw = null;
        /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
        try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
        /* Resource Cleanup */
        ftpReader.Close();
        ftpStream.Close();
        ftpResponse.Close();
        ftpRequest = null;
        /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
        try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return directoryList; }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    /* Return an Empty string Array if an Exception Occurs */
    return new string[] { "" };
}

/* List Directory Contents in Detail (Name, Size, Created, etc.) */
public string[] directoryListDetailed(string directory)
{
    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
        /* Establish Return Communication with the FTP Server */
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        /* Establish Return Communication with the FTP Server */
        ftpStream = ftpResponse.GetResponseStream();
        /* Get the FTP Server's Response Stream */
        StreamReader ftpReader = new StreamReader(ftpStream);
        /* Store the Raw Response */
        string directoryRaw = null;
        /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
        try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
        /* Resource Cleanup */
        ftpReader.Close();
        ftpStream.Close();
        ftpResponse.Close();
        ftpRequest = null;
        /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
        try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return directoryList; }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    /* Return an Empty string Array if an Exception Occurs */
    return new string[] { "" };
}
}

}

这是我的脚本

ftp ftpClient = new ftp(@"ftp://*******.*******.fr", "*************", "************");
ftpClient.upload(filename, sourcezip);
string fileSize = ftpClient.getFileSize(filename);
ftpClient = null;

和服务器上的结果

【问题讨论】:

  • 你能澄清你的问题吗?您说它不会创建一个空文件,但它确实会,我想您可能想说的是它不会上传文件,它只是创建一个空文件。会是对的吗?你有什么错误吗?您是否尝试过调试它并单步执行您的代码?
  • 是的,它不会上传文件。我在 FTP 服务器或应用程序上没有错误。该过程运行得很好,通常会结束。 (对不起我的英语不好)
  • 显示相关代码。创建几行重现问题,然后从那里开始调试。
  • 问题是他通过FileMode.Create打开它来截断他上传的每个文件。
  • @AdamKDean 哈哈,很好发现。

标签: c# upload ftp


【解决方案1】:

我注意到在您的上传方法中您使用的是FileMode.Create

FileStream localFileStream = new FileStream(localFile, FileMode.Create);

也许你应该把它改成FileMode.Open

FileStream localFileStream = new FileStream(localFile, FileMode.Open);

FileMode.Create的描述:

指定操作系统应该创建一个新文件。 如果 文件已经存在,它将被覆盖。 这需要 System.Security.Permissions.FileIOPermissionAccess.Write 权限。 FileMode.Create 相当于请求如果文件没有 存在,使用 System.IO.FileMode.CreateNew;否则,使用 System.IO.FileMode.Truncate。如果文件已经存在但是是 隐藏文件,System.UnauthorizedAccessException 异常是 扔了。

FileMode.Open的描述:

指定操作系统应打开现有文件。这 打开文件的能力取决于指定的值 System.IO.FileAccess 枚举。一个 System.IO.FileNotFoundException 如果文件不存在则抛出异常。

【讨论】:

  • 谢谢,但我想上传任何文件。因此需要使用“FileMode.Create”。我的问题是我的文件只是创建而不上传
  • 我不明白你的意思。您的代码所做的是上传一个空白文件,这就是您设计的方式。您将文件名传递给它,它会截断local file 并上传空白local file。它不会在远程服务器上创建一个空白文件,而是在local 机器上创建一个空白文件并上传。
  • 始终与 FileMode.open 相同
  • @Atoxis 可能是因为您正在使用同一个文件进行测试,现在该文件在您的磁盘上为 0 字节。
猜你喜欢
  • 2023-03-11
  • 2014-03-03
  • 1970-01-01
  • 2012-10-30
  • 1970-01-01
  • 1970-01-01
  • 2012-05-13
  • 2013-04-25
  • 1970-01-01
相关资源
最近更新 更多