2016-12-19 41 views
-1

我試圖將文件從本地計算機複製到使用C#的FTP服務器。 當我使用下面的代碼時,該文件被完全複製到FTP服務器,但是**原始行被剪切成只有512字節長的段,而它們應該是1152,1126或1024字節長。 **我使用的示例文件具有現在16行,而不是7.流只使用C#向FTP服務器上的文件寫入512字節#

public void uploadLOTFILE(string username, string password) 
    { 
     FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://mysite.mine/mypathandfilename"); 
     request.Method = WebRequestMethods.Ftp.UploadFile; 
     request.Credentials = new NetworkCredential(username, password); 
     request.KeepAlive = true; 
     System.IO.Stream rs = request.GetRequestStream(); 

     var lines = File.ReadLines(@"myLocalFile.txt"); 
     foreach (var line in lines) 
     { 
      byte[] buffer = Encoding.ASCII.GetBytes(line);     
      Console.WriteLine("buffer.length:" + buffer.Length.ToString()); 
      rs.Write(buffer,0,buffer.Length); 
     } 
     rs.Close(); 

     FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 

     Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription); 

     response.Close(); 
     } 

從Console.WriteLine命令輸出中的示例文件:

buffer.length:1152

緩衝器。長度:1126

buffer.length:1152

buffer.length:1152

buffer.length:1152

buffer.length:1152

buffer.length:1024

我還用從MSDN(https://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx)確切的拷貝,但此有相同結果。

編輯: 還試圖以下代碼: 串文件路徑= @ 「myFilePath」; var fileName = Path.GetFileName(filePath); var request =(FtpWebRequest)WebRequest.Create(「ftp://myftp」);

 request.Method = WebRequestMethods.Ftp.UploadFile; 
     request.Credentials = new NetworkCredential(username, password); 
     request.UsePassive = true; 
     request.UseBinary = true; 
     request.KeepAlive = false; 

     using (var fileStream = File.OpenRead(filePath)) 
     { 
      using (var requestStream = request.GetRequestStream()) 
      { 
       fileStream.CopyTo(requestStream); 
       requestStream.Close(); 
      } 
     } 

它給出了相同的結果。該文件被完全複製,但每512個字節添加一個換行符。

使用FileZilla,我可以對相同類型的文件進行正確的FTP傳輸。

+0

*「文件完全複製到FTP服務器,但行只有512字節長」* - 這沒有意義。那麼文件是否完全複製? –

+0

你如何檢查線路長度只有512線? –

+0

你究竟在做什麼?你爲什麼要用文件上傳文件? –

回答

0

我解決了我的問題,使用可通過cmd訪問的內置窗口FTP。

  string[] lines = { username, password, "remote directory", "put " + "\"" + filePath + "\"" , "bye"}; 
     // WriteAllLines creates a file, writes a collection of strings to the file, 
     // and then closes the file. You do NOT need to call Flush() or Close(). 
     System.IO.File.WriteAllLines("full file path of your script", lines); 
     Process cmd = new Process(); 
     cmd.StartInfo.FileName = "cmd.exe"; 
     cmd.StartInfo.RedirectStandardInput = true; 
     cmd.StartInfo.RedirectStandardOutput = true; 
     cmd.StartInfo.CreateNoWindow = true; 
     cmd.StartInfo.UseShellExecute = false; 
     cmd.Start(); 

     cmd.StandardInput.WriteLine(@"ftp -s:" + "\"" + "full file path of your script" + "\"" + " remote device"); 
     cmd.StandardInput.Flush(); 
     cmd.StandardInput.Close(); 
     cmd.WaitForExit();