C# WebClient将文件下载到0KB?
我需要覆盖的文件在本地计算机上。我正在检索的文件来自我的FTP服务器。这些文件的名称相同,但字节不同,例如,它们已更新 我使用本地计算机上的文件作为目标文件-这意味着我使用它们的名称在FTP服务器上轻松找到它们 这是我写的代码:C# WebClient将文件下载到0KB?,c#,webclient,C#,Webclient,我需要覆盖的文件在本地计算机上。我正在检索的文件来自我的FTP服务器。这些文件的名称相同,但字节不同,例如,它们已更新 我使用本地计算机上的文件作为目标文件-这意味着我使用它们的名称在FTP服务器上轻松找到它们 这是我写的代码: private void getFiles () { string startupPath = Application.StartupPath; /* * This finds the files within the users insta
private void getFiles () {
string startupPath = Application.StartupPath;
/*
* This finds the files within the users installation folder
*/
string[] files = Directory.GetFiles(startupPath + "\\App_Data", "*.*",
SearchOption.AllDirectories);
foreach (string s in files)
{
/*
* This gets the file name
*/
string fileName = Path.GetFileName(s);
/*
* This gets the folder and subfolders after the main directory
*/
string filePath = s.Substring(s.IndexOf("App_Data"));
downloadFile("user:pass@mysite.tk/updates/App_Data/" + fileName,
startupPath + "\\" + filePath);
}
}
private void downloadFile (string urlAddress, string location)
{
using (WebClient webClient = new WebClient())
{
System.Uri URL = new System.Uri("ftp://" + urlAddress);
webClient.DownloadFileAsync(URL, location);
}
}
代码完成后,由于某种原因,子文件夹中的文件显示为0KB。这很奇怪,因为我知道FTP服务器上的每个文件都大于0KB
我的问题是:为什么子文件夹中的文件显示为0KB
如果这篇文章不清楚,请让我知道,我会尽力澄清。在回答评论中的问题时,以下是一种可能的方法,但是不清楚
getFiles
是否应该是一种阻止方法。在我的示例中,我假设它是(在所有下载完成之前,该方法不会退出)。我不确定它的功能,因为我是在脑子里写的,但这是一个一般的想法
private void getFiles () {
string startupPath = Application.StartupPath;
/*
* This finds the files within the users installation folder
*/
string[] files = Directory.GetFiles(startupPath + "\\App_Data", "*.*",
SearchOption.AllDirectories);
using (WebClient client = new WebClient())
{
int downloadCount = 0;
client.DownloadDataCompleted +=
new DownloadDataCompletedEventHandler((o, e) =>
{
downloadCount--;
});
foreach (string s in files)
{
/*
* This gets the file name
*/
string fileName = Path.GetFileName(s);
/*
* This gets the folder and subfolders after the main directory
*/
string filePath = s.Substring(s.IndexOf("App_Data"));
downloadFile(client, "user:pass@mysite.tk/updates/App_Data/" + fileName,
startupPath + "\\" + filePath);
downloadCount++;
}
while (downloadCount > 0) { }
}
}
private void downloadFile (WebClient client, string urlAddress, string location)
{
System.Uri URL = new System.Uri("ftp://" + urlAddress);
client.DownloadFileAsync(URL, location);
}
您可以使用FTPWebRequest进行此操作
不太熟悉
WebClient
,但在下载完成之前它不会被处理掉吗?(因为您使用的是DownloadFileAsync)同样,WebClient的正确功能是什么,用于将文件下载/覆盖到我的本地计算机?我的问题仍然是:我正在下载的文件显示为0KB。您是否可以验证您是否有权将文件写入输出目录?此外,您可能需要向客户端添加Accept Encoding
头。