2014-06-16 37 views
0

我一直在嘗試上傳多個XML文件到服務器。但是,當我收到此錯誤爲目錄沒有發現異常,我仍然可以看到我的文件在同一目錄中。上傳多個文件到FTP服務器 - 目錄未找到異常未處理

這裏是我的代碼:

String ftpurl = "100.100.0.35/Vin"; // e.g. fake IDs 
String ftpusername = "ftp";   // e.g. fake username 
String ftppassword = "Password"; // e.g. fake password 

string path = @"C:\\Users\\Desktop\\LUVS\\"; 
// string[] filePaths = Directory.GetFiles(sourcefilepath, "*.xml", SearchOption.AllDirectories); 
// string[] filePaths = Directory.GetFiles(@"C:\\Users\Desktop\\LUVS/", "*.xml", SearchOption.AllDirectories); 
string[] filePaths = Directory.GetFiles(path, @"*.xml", SearchOption.AllDirectories); 

// Work with each file individually 
foreach (var files in filePaths) 
{ 
    string filename = Path.GetFileName(path); 
    string ftpfullpath = "ftp://" + ftpurl + "/" + filename; 
    FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath); 
    ftp.Credentials = new NetworkCredential(ftpusername, ftppassword); 
    ftp.KeepAlive = true; 
    ftp.UseBinary = true; 
    ftp.Method = WebRequestMethods.Ftp.UploadFile; 

    FileStream fs = File.OpenRead(path); 
    byte[] buffer = new byte[fs.Length]; 
    fs.Read(buffer, 0, buffer.Length); 
    fs.Close(); 

    Stream ftpstream = ftp.GetRequestStream(); 
    ftpstream.Write(buffer, 0, buffer.Length); 
    ftpstream.Close(); 
} 
+1

首先循環,你的FileStream是開放的路徑本身,而不是在文件那條路。 –

+0

那太傻了我怎麼錯過了,謝謝艾哈邁德。 – shruthi

回答

0

您在foreach循環中所犯的錯誤,替換爲以下

  foreach (var file in filePaths) 
      { 

       string filename = Path.GetFileName(file); 
       string ftpfullpath = "ftp://" + ftpurl + "/" + filename; 
       FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath); 
       ftp.Credentials = new NetworkCredential(ftpusername, ftppassword); 

       ftp.KeepAlive = true; 
       ftp.UseBinary = true; 
       ftp.Method = WebRequestMethods.Ftp.UploadFile; 

       FileStream fs = File.OpenRead(file); 
       byte[] buffer = new byte[fs.Length]; 
       fs.Read(buffer, 0, buffer.Length); 
       fs.Close(); 

       Stream ftpstream = ftp.GetRequestStream(); 
       ftpstream.Write(buffer, 0, buffer.Length); 
       ftpstream.Close(); 


      }