2012-04-26 11 views
12

Sto creando un semplice drag-file-e-upload-automaticamente-to-FTP applicazione delle finestrefile Caricamento di FTP sono danneggiati una volta nelle strette

enter image description here

e sto usando il MSDN code a carica il file sull'FTP.

Il codice è piuttosto semplice:

// Get the object used to communicate with the server. 
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(String.Format("{0}{1}", FTP_PATH, filenameToUpload)); 
request.Method = WebRequestMethods.Ftp.UploadFile; 

// Options 
request.UseBinary = true; 
request.UsePassive = false; 

// FTP Credentials 
request.Credentials = new NetworkCredential(FTP_USR, FTP_PWD); 

// Copy the contents of the file to the request stream. 
StreamReader sourceStream = new StreamReader(fileToUpload.FullName); 
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(); 
writeOutput("Upload File Complete!"); 
writeOutput("Status: " + response.StatusDescription); 

response.Close(); 

e lo fa ottenere caricati sul FTP

enter image description here

Il problema è quando vedo il file su un browser, o semplicemente scarica e prova a vederlo sul desktop:

enter image description here

Ho già utilizzato request.UseBinary = false; e request.UsePassive = false; ma non crea alcun tipo di buono.

Quello che ho scoperto è che, il file originale ha 122Kb lunghezza e nel FTP (e dopo il download), ha 219KB ...

Che cosa sto facendo di sbagliato?

A proposito, il metodo uploadFileToFTP() è in esecuzione all'interno di un BackgroundWorker, ma io in realtà non cosa che fa la differenza ...

+0

dati binari e UTF-8 non mescolare bene. – dtb

+0

@dtb usando 'Encoding.ASCII.GetBytes (sourceStream.ReadToEnd());' ottiene lo stesso comportamento ... – balexandre

+0

Sigh. ** I dati binari ** e ** caratteri ** sono due cose diverse. Sì, puoi codificare i caratteri in byte, ma non puoi decodificare ciecamente i byte che non codificano i caratteri. – dtb

risposta

31

Non si deve usare uno StreamReader, ma solo un flusso di leggere file binari.

Streamreader è progettato per leggere solo file di testo.

prova con questo:

private static void up(string sourceFile, string targetFile) 
{    
    try 
    { 
     string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"]; 
     string ftpUserID = ConfigurationManager.AppSettings["ftpUser"]; 
     string ftpPassword = ConfigurationManager.AppSettings["ftpPass"]; 
     ////string ftpURI = ""; 
     string filename = "ftp://" + ftpServerIP + "//" + targetFile; 
     FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename); 
     ftpReq.UseBinary = true; 
     ftpReq.Method = WebRequestMethods.Ftp.UploadFile; 
     ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword); 

     byte[] b = File.ReadAllBytes(sourceFile); 

     ftpReq.ContentLength = b.Length; 
     using (Stream s = ftpReq.GetRequestStream()) 
     { 
      s.Write(b, 0, b.Length); 
     } 

     FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse(); 

     if (ftpResp != null) 
     { 
      MessageBox.Show(ftpResp.StatusDescription); 
     } 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.ToString()); 
    } 
} 
+0

Quello ha funzionato. Grazie! –

+1

@ user2212907: se ti ha aiutato a sviare la risposta in modo che aiuti gli altri;) – LaGrandMere

+0

Siamo spiacenti! Ho dimenticato di andare su: P Fatto! –

3

i problemi sono causati dal codice decodifica dei dati binari a carattere dati e ritorno ai dati binari. Non farlo.


Utilizzare il UploadFile Method del WebClient Class:

using (WebClient client = new WebClient()) 
{ 
    client.Credentials = new NetworkCredential(FTP_USR, FTP_PWD); 
    client.UploadFile(FTP_PATH + filenameToUpload, filenameToUpload); 
} 
+1

quasi duplicato. Quella classe non è buona. Genera eccezioni come l'inferno. Non è stato possibile eseguire il caricamento. –

+0

Hai salvato la mia vita da fratello, perché la gente usa quel fastidioso codice, questo è il migliore +1 –

Problemi correlati