PK-1825
PK-1825

Reputation: 1489

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

Upvotes: 2

Views: 4653

Answers (2)

Raul
Raul

Reputation: 3121

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.

Upvotes: 3

PK-1825
PK-1825

Reputation: 1489

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.

Upvotes: 0

Related Questions