简体   繁体   中英

Upload multiple files to ftp server - Directory not found exception unhandled

I have been trying to upload multiple xml files to server. But when I receive this error as Directory not found exception and I can still see my files in the same directory.

Here is my code:

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();
}

You made mistakes in the foreach loop, replace the loop with the following

            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();


            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM