問題描述
我已經搜索和搜索,但找不到這樣做的方法.我在要上傳的目錄中有文件.文件名不斷變化,所以我無法按文件名上傳.這是我嘗試過的.
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.
有沒有人可以通過 WebClient
上傳文件目錄的好方法?
Does anyone have a good way to upload a directory of files via WebClient
?
推薦答案
你必須定義和設置文件
.如果您想上傳某個本地目錄中的所有文件,例如使用 Directory.EnumerateFiles
.
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
.
也是 address 參數noreferrer">WebClient.UploadFile
必須是目標文件的完整 URL,而不僅僅是目標目錄的 URL.
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);
}
}
有關遞歸上傳,請參閱:
C#遞歸上傳到FTP服務器
For a recursive upload, see:
Recursive upload to FTP server in C#
這篇關于使用 WebClient 將文件目錄上傳到 FTP 服務器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!