简体   繁体   中英

How to save downloaded file to local folder?

I want to store file which is coming from API, i have tried the below code but it is giving error.

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

Error: An exception occurred during a WebClient request. Inner Exception: The filename, directory name, or volume label syntax is incorrect.

how i can download file from web and store it my local folder? i need to save that path in database

The WebClient.DownloadFile method requires the filename where to download the file, not just the directory. So either pass just the filename and it will save the file to the apps directory or provide the fully qualified path.

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

The same goes for the source file. Here is the doc .

Also take a look at c# naming conventions as local variables are usually lower case.

I solve it,

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

before i wasn't added filename, so we need to add filename, in my case it is filenameWithoutPath, it is working now.

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