0

I wrote this code to download a file from an FTP server. When the program tries to download and save the file, I get an access denied error. I tried opening the program with admin rights, but it gives the same error.

WebClient request = new WebClient();
request.Credentials = new NetworkCredential(txtFTPuser.Text,
                                            txtFTPpassword.Text);
/*List all directory files*/
byte[] fileData = request.DownloadData(fullDownloaPath);//dnoces.dreamhost.com
FileStream fi = File.Create(downloadTo);
fi.Write(fileData, 0, fileData.Length);
fi.Close();
MessageBox.Show("Completed!");

enter image description here

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
funerr
  • 7,212
  • 14
  • 81
  • 129

3 Answers3

7

You need to provide the full file path in your call to File.Create. Right now, you're trying to overwrite your "Games" directory with the file you're downloading, and that's no good.

Try setting downloadTo to something like C:\Users\agam\Desktop\Games\myfile.ext instead of, as it's likely set to now, C:\Users\agam\Desktop\Games\.


As an aside, there are two obvious improvements to your code I'd encourage you to look at:

For example:

using (WebClient request = new WebClient())
{
    request.Credentials = new NetworkCredential(txtFTPuser.Text,
                                                txtFTPpassword.Text);
    request.DownloadFile(fullDownloadPath, downloadTo);
    MessageBox.Show("Completed!");
}
Community
  • 1
  • 1
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
  • Thanks, I have scrambled with the paths until I got it right. I didn't think it would be that easy. I am trying to figure this out for about 3 days now. You've made my day(night) :) B.W. I see the using(){} a lot, what does it do? thanks. – funerr Oct 10 '11 at 16:40
1

What is the value of "downloadTo" when the file create is called? If "download to" is the games directory rather than the full path of that target file, you'd probably get that error message, since you'd be trying to overwrite a (probably open) directory with a file.

Erik Dietrich
  • 6,080
  • 6
  • 26
  • 37
0

you will need to do two things, if you are running it from visual studio, try opening visual studio as Administrator, or add the current user with elevated rights.