Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
801 views
in Technique[技术] by (71.8m points)

c# - Upload directory of files to FTP server using WebClient

I have searched and searched and cannot find a way to do this. I have files in a directory I want to upload. The file names change constantly so I cannot upload by file name. Here is what I have tried.

using (WebClient client = new WebClient())
{
    client.Credentials = new NetworkCredential("User", "Password");
    foreach (var filePath in files)
        client.UploadFile("ftp://site.net//PICS_CAM1//", "STOR", @"PICS_CAM1");
}

But I am getting a compiler error:

The name 'files' does not exist in the current context

Everything I have researched says this should work.

Does anyone have a good way to upload a directory of files via WebClient?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to define and set the files. If you wanted to upload all files in a certain local directory, use for example Directory.EnumerateFiles.

Also the address argument of WebClient.UploadFile has to be a full URL to a target file, not just a URL to a target directory.

IEnumerable<string> files = Directory.EnumerateFiles(@"C:localfolder");

using (WebClient client = new WebClient())
{
    client.Credentials = new NetworkCredential("username", "password");

    foreach (string file in files)
    {
        client.UploadFile(
            "ftp://example.com/remote/folder/" + Path.GetFileName(file), file);
    }
}

For a recursive upload, see:
Recursive upload to FTP server in C#


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...