2017-06-21 146 views
1

我需要從一個服務器上的FTP文件傳輸到其他。我已經使用了下面的代碼。FTP文件傳輸C#

了許多文件,這部分只傳輸一個文件。例如。我有一個56KB的源文件。運行下面的代碼之後,源文件被減小到0KB和0KB文件被傳輸到目標,而不是56 KB文件大小。

我編譯後的代碼將所有文件從源傳輸到目的地。但是,如上所述,在傳輸單個0KB文件後,它不會進一步發展。

請幫幫我。

static void Main(string[] args) 

    { 


    string DISCH_DEST = System.Configuration.ConfigurationManager.AppSettings["DISCH_DEST"]; //Contains the source folder in source server 
    string FTP_DISCH = System.Configuration.ConfigurationManager.AppSettings["FTP_DISCH"]; // FTP path (ftp://***********/) 
    string USERNAME = System.Configuration.ConfigurationManager.AppSettings["USERNAME"]; 
    string PASSWORD = System.Configuration.ConfigurationManager.AppSettings["PASSWORD"]; 



    DirectoryInfo DISCH_Directory = new DirectoryInfo(DISCH_DEST); 

    FileInfo[] DISCH_Files = DISCH_Directory.GetFiles("*.*"); 

    foreach (var f in DISCH_Files) //FETCHING FILES FROM THE BULK FOLDER (IN) 

       { 


        string FN = Path.GetFileName(f.FullName); 
        int bufferSize = 1024; 

        FtpWebRequest REQ = (FtpWebRequest)WebRequest.Create(new Uri(String.Format("{0}/{1}",FTP_DISCH,FN))); 
        REQ.Credentials = new NetworkCredential(USERNAME, PASSWORD); 

        REQ.Method = WebRequestMethods.Ftp.UploadFile;      
        Stream FTP_Stream = REQ.GetRequestStream(); 

        FileStream LOCAL_FileStream = new FileStream(f.FullName, FileMode.Create); 
        byte[] bytebuffer = new byte[bufferSize]; 
        int bytesSent = FTP_Stream.Read(bytebuffer, 0, bufferSize); 

        try 
        { 
         while (bytesSent != 0) 
         { 
          LOCAL_FileStream.Write(bytebuffer, 0, bytesSent); 
          bytesSent = FTP_Stream.Read(bytebuffer, 0, bytesSent); 

         } 

        } 

        catch (Exception ex) { Console.WriteLine(ex.ToString()); } 

        LOCAL_FileStream.Close(); 
        FTP_Stream.Close(); 
        REQ = null; 


       } 


      } 

在許多文件中,這只是部分傳輸單個文件。例如。我有一個56KB的源文件。在運行下面的代碼後,源文件將減少到0kb,並將0KB文件傳輸到目標文件,而不是56 KB的文件大小。

我構建的代碼將所有文件從源傳輸到目標。但是,如上所述,在傳輸單個0KB文件後,它不會進一步發展。

請幫幫我。

+0

的可能的複製[上傳和FTP服務器在C#中下載的二進制文件到//NET](https://開頭計算器。 COM /問題/ 44606028 /上傳和下載,一個二進制文件到從-FTP服務器功能於C-NET) –

回答

1

現在我不明白爲什麼你的代碼會發送任何文件。

您的代碼:

Stream FTP_Stream = REQ.GetRequestStream(); 

FileStream LOCAL_FileStream = new FileStream(f.FullName, FileMode.Create); 
byte[] bytebuffer = new byte[bufferSize]; 
int bytesSent = FTP_Stream.Read(bytebuffer, 0, bufferSize); 

你正在做一個新的數據流,然後從FTP服務器讀取擺在它...

如果你發送它不會是一個的FileMode文件創建一個新文件,但FileMode.Open。

你也肯定會從LOCAL_FileStream讀寫FTP_STream ....