C# 如何将下载的文件保存到本地文件夹?

C# 如何将下载的文件保存到本地文件夹?,c#,webclient,C#,Webclient,我想存储来自API的文件,我已经尝试了下面的代码,但它给出了错误 string StrFileName = result.LabelDownload.Href; string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString(); string dir = string.Format("{0}{1:yyyy-MM}\\", FilePath, DateTime.Now); // Save the upload

我想存储来自API的文件,我已经尝试了下面的代码,但它给出了错误

string StrFileName = result.LabelDownload.Href;
string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
string dir = string.Format("{0}{1:yyyy-MM}\\", FilePath, DateTime.Now);

   // Save the uploaded file.               
   if (!Directory.Exists(dir))
     Directory.CreateDirectory(dir);

    WebClient wc = new WebClient();
    wc.DownloadFile(StrFileName, dir);
错误:WebClient请求期间发生异常。 内部异常:文件名、目录名或卷标语法不正确


如何从web下载文件并将其存储到本地文件夹?我需要将该路径保存在数据库中,
WebClient.DownloadFile
方法需要下载文件的文件名,而不仅仅是目录。因此,要么只传递文件名,它就会将文件保存到apps目录,要么提供完全限定的路径

string sourceFileName =   
result.LabelDownload.Href;
string filePath = ConfigurationManager.AppSettings["FilePath"].ToString();
string dir = string.Format("{0}{1:yyyy-MM}", filePath, DateTime.Now);

   // Save the uploaded file.               
   if (!Directory.Exists(dir))
     Directory.CreateDirectory(dir);

    WebClient wc = new WebClient();
    wc.DownloadFile(sourceFileName, Path.Combine(dir, sourceFileName));
源文件也是如此。这是你的电话号码

还可以看看局部变量通常是小写。

我解决了它

WebClient wc = new WebClient();
wc.DownloadFile(StrFileName, dir + filenameWithoutPath);

在我没有添加文件名之前,我们需要添加文件名,在我的情况下,它是filename WithoutPath,现在可以工作。

这个问题与HTML或ASP.NET无关。第二个参数是文件名,而不是目录名
DownloadFile
也可以使用相对文件名。OP发布了一个字典名而不是文件名,虽然我在编写文件夹名时会跳过最后一个(转义的)反斜杠
\\
,并让下面的
路径。Combine
执行magic@PanagiotisKanavos当然实际上,我想指出文件名是必需的,但没有明确说明correctly@GianPaolo未能删除斜杠,谢谢。这就是我使用路径的原因。组合这是创建绝对路径的错误方法。使用
Path.combined
,以避免由于多余或缺少反斜杠而出现问题。另一方面,相对路径可以很好地工作。只需指定文件名即可将文件存储在当前目录中