2012-05-07 1 views
3

내부 및 FTP 서버에 일부 데이터를 업로드해야합니다.C# FTP 서버 내부에 바이트 []를 업로드하십시오.

내부 및 FTP 파일을 업로드하는 방법에 대한 stackoverflow 게시물이 모두 작동합니다.

이제 업로드를 개선하려고합니다.

대신 DATA를 수집하고 FILE에 기록한 다음 FTP에 파일을 업로드합니다. DATA를 수집하고 로컬 파일을 만들지 않고 업로드하려고합니다.

일이 무엇인지 이제
string uri = "ftp://" + ftpServerIp + "/" + fileToUpload.Name; 
System.Net.FtpWebRequest reqFTP; 
// Create FtpWebRequest object from the Uri provided 
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIp + "/" + fileToUpload.Name)); 
// Provide the WebPermission Credintials 
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 
// By default KeepAlive is true, where the control connection is not closed after a command is executed. 
reqFTP.KeepAlive = false; 
// Specify the command to be executed. 
reqFTP.Method = WebRequestMethods.Ftp.UploadFile; 
// Specify the data transfer type. 
reqFTP.UseBinary = true; 
byte[] messageContent = Encoding.ASCII.GetBytes(message); 
// Notify the server about the size of the uploaded file 
reqFTP.ContentLength = messageContent.Length; 
int buffLength = 2048; 
// Stream to which the file to be upload is written 
Stream strm = reqFTP.GetRequestStream(); 
// Write Content from the file stream to the FTP Upload Stream 
int total_bytes = (int)messageContent.Length; 
while (total_bytes > 0) 
{ 
    strm.Write(messageContent, 0, buffLength); 
    total_bytes = total_bytes - buffLength; 
} 
strm.Close(); 

은 다음과 같다 :

내가 다음을 수행이를 달성하기 위해
  1. 내가 파일이 생성되는 서버
  2. 에 연결하는 클라이언트를 참조
  3. 데이터가 전송되지 않음
  4. 어떤 시점에서 스레드가 종료 됨 연결이 닫혔습니다
  5. 업로드 된 파일이 비어 있는지 확인하십시오.

내가 전송하려는 DATA는 STRING TYPE이므로, 그 이유는 byte []입니다. messageContent = Encoding.ASCII.GetBytes (message);

무엇이 잘못 되었나요?

또한 : ASCII.GetBytes로 날짜를 인코딩하면 원격 서버에서 TEXT 파일이나 일부 바이트가있는 파일이 생깁니 까?

이 어떤 제안을 주셔서 감사

나는 코드를 볼 수
+0

STRM : 당신이 청크 데이터를 기록해야하는 경우

Stream strm = reqFTP.GetRequestStream(); strm.Write(messageContent, 0, messageContent.Length); strm.Close(); 

, 당신은 배열의 오프셋 (offset)를 추적 할 필요가 .Write (messageContent, 0, messageContent.lenght); 솔루션입니다. 그냥이 모든 파일을 한 번에 쓸 것이라고 생각하고 거대한 파일이 어떻게 될지 알지 못합니다. – NoobTom

답변

4

한 가지 문제는 반복 될 때마다 서버에 같은 바이트를 작성하는 것입니다 :

while (total_bytes > 0) 
{ 
    strm.Write(messageContent, 0, buffLength); 
    total_bytes = total_bytes - buffLength; 
} 

당신은을 변경해야

while (total_bytes < messageContent.Length) 
{ 
    strm.Write(messageContent, total_bytes , bufferLength); 
    total_bytes += bufferLength; 
} 
1

보다 많은 데이터를 쓰려고합니다. 코드는 한 번에 2048 바이트의 블록을 씁니다. 데이터가 적 으면 write 메서드에 배열 외부에있는 바이트에 액세스하려고 시도합니다. 물론 그렇지 않습니다.

모든 사용자가 데이터를 작성해야한다은 다음과 같습니다

int buffLength = 2048; 
int offset = 0; 

Stream strm = reqFTP.GetRequestStream(); 

int total_bytes = (int)messageContent.Length; 
while (total_bytes > 0) { 

    int len = Math.Min(buffLength, total_bytes); 
    strm.Write(messageContent, offset, len); 
    total_bytes -= len; 
    offset += len; 
} 

strm.Close();