Posted By

kyrathaba on 12/05/10


Tagged

download upload FTP c#


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Priestd09


C# FTP Upload & Download


 / Published in: C#
 

URL: http://kyrathaba.dcmembers.com/errata/ftp.htm

Not extensively tested, but seems to work in my sample project.

uses the class I posted here: http://www.snipplr.com/view/46669/minimist-c-errorlogging-class/

  1. namespace Kyrathasoft.NetUtilities.FTPclient {
  2.  
  3. //developed this class on Saturday, 01/01/2011
  4. //added method DirectoryDetails() on 01/02/2011
  5.  
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Net;
  10. using System.Text;
  11. using Kyrathasoft.Dialogs.ErrLogging;
  12.  
  13. public class clsFTPclient {
  14.  
  15. public string NL = Environment.NewLine;
  16.  
  17. /* A few points to remember:
  18.   *
  19.   * WebRequest.Create takes the FULL URL including
  20.   * path AND file name. To work with a file specify the
  21.   * full path name e.g. ftp://localhost/folder/test/myfile.zip.
  22.   * To work with a folder/directory, specify the full path,
  23.   * e.g. ftp://localhost/folder/test/
  24.   * You cannot upload a file to ftp://localhost/folder/test/, you
  25.   * have to specify the filename when you create the WebRequest.
  26.   *
  27.   * The WebRequestMethods.Ftp enum contains a list of actions
  28.   * you can perform. These include:
  29.   *
  30.   * AppendFile – Append a file to an existing file on an FTP
  31.   * server (FTP APPE)
  32.   *
  33.   * DeleteFile – Delete a file on an FTP
  34.   * server (FTP DELE)
  35.   *
  36.   * DownloadFile – Download a file from an FTP
  37.   * server (FTP RETR)
  38.   *
  39.   * GetFileSize – Retrieve the size of a file on an FTP
  40.   * server (FTP SIZE)
  41.   *
  42.   * ListDirectory – Gets a short listing of the files on an
  43.   * FTP server (FTP NLIST)
  44.   *
  45.   * ListDirectoryDetails – Gets a detailed listing of the files on
  46.   * an FTP server (FTP LIST)
  47.   *
  48.   * MakeDirectory – Creates a directory on an
  49.   * FTP server (FTP MKD)
  50.   *
  51.   * RemoveDirectory – Method that removes a directory (FTP RM)
  52.   *
  53.   * Rename – Renames a directory (FTP RENAME)
  54.   *
  55.   * UploadFile – Uploads a file to an FTP server (FTP STOR)
  56.   *
  57.   * UploadFileWithUniqueName – Uploads a file with a unique name to
  58.   * an FTP server (FTP STOU)
  59.   *
  60.   */
  61.  
  62. #region clsFTPclient_PrivateMembers
  63.  
  64. // The hostname or IP address of the FTP server
  65. private string _remoteHost;
  66.  
  67. // The remote username
  68. private string _remoteUser;
  69.  
  70. // Password for the remote user
  71. private string _remotePass;
  72.  
  73. #endregion
  74.  
  75. #region clsFTPclient_Constructors
  76.  
  77. //constructor
  78. public clsFTPclient(string remoteHost, string remoteUser,
  79. string remotePassword) {
  80. _remoteHost = remoteHost;
  81. _remoteUser = remoteUser;
  82. _remotePass = remotePassword;
  83. }
  84.  
  85. #endregion
  86.  
  87. #region clsFTPclient_Methods
  88.  
  89. public List<clsDirDetails> DirectoryDetails(string subdirectory) {
  90.  
  91. List<clsDirDetails> the_details = new List<clsDirDetails>();
  92. clsDirDetails details;
  93.  
  94. // Get the object used to communicate with the server.
  95. FtpWebRequest request =
  96. (FtpWebRequest)WebRequest.Create(_remoteHost + subdirectory);
  97. request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  98.  
  99. request.Credentials =
  100. new NetworkCredential(_remoteUser, _remotePass);
  101.  
  102. FtpWebResponse response = (FtpWebResponse)request.GetResponse();
  103. Stream responseStream = response.GetResponseStream();
  104. StreamReader reader = new StreamReader(responseStream);
  105.  
  106. while (!reader.EndOfStream) {
  107. details = new clsDirDetails();
  108. //once .Unparsed is set, clsDirDetails internally calcs
  109. //and assigns DirMemberType, LastModified and PathOrFilename
  110. //These assignments are made just as soon as the .Unparsed
  111. //property is set, BEFORE details are added to the List
  112. details.Unparsed = reader.ReadLine();
  113. the_details.Add(details);
  114. }
  115.  
  116. return the_details;
  117. }
  118.  
  119. public List<string> DirectoryListing(string subdirectory) {
  120.  
  121. /* Examples of how to invoke:
  122.   *
  123.   *
  124.   *
  125.   *
  126.   * sample button click_event handler follows...
  127.   * =============================================================
  128.   string username = "myUsername";
  129.   string password = "myPassword";
  130.   string host = "ftp://myWebsite.com";
  131.  
  132.  
  133.   clsFTPclient client = new clsFTPclient(host, username, password);
  134.   //gives root directory listing
  135.   List<string> files = client.DirectoryListing("");
  136.   label1.Text = files.Count.ToString();
  137.   textBox1.Text = string.Empty;
  138.   foreach (string s in files) {
  139.   textBox1.Text += s + NL;
  140.   }
  141.   * ============================================================
  142.   *
  143.   *
  144.   *
  145.   ................
  146.   *
  147.   *
  148.   *
  149.   * another sample button click_event handler follows...
  150.   * ===========================+================================
  151.   string username = "my_username";
  152.   string password = "my_password";
  153.   string host = "ftp://mywebsite.com";
  154.  
  155.  
  156.   clsFTPclient client = new clsFTPclient(host, username, password);
  157.   //lists the /httpdocs/non_church subdirectory
  158.   List<string> files = client.DirectoryListing("//httpdocs//non_church");
  159.   label1.Text = files.Count.ToString();
  160.   textBox1.Text = string.Empty;
  161.   foreach (string s in files) {
  162.   textBox1.Text += s + NL;
  163.   }
  164.   * ============================================================ */
  165.  
  166.  
  167. List<string> result = new List<string>();
  168.  
  169. try {
  170. FtpWebRequest request =
  171. (FtpWebRequest)WebRequest.Create(_remoteHost + subdirectory);
  172. request.Method = WebRequestMethods.Ftp.ListDirectory;
  173. request.Credentials =
  174. new NetworkCredential(_remoteUser, _remotePass);
  175. FtpWebResponse response = (FtpWebResponse)request.GetResponse();
  176. Stream responseStream = response.GetResponseStream();
  177. StreamReader reader = new StreamReader(responseStream);
  178.  
  179. while (!reader.EndOfStream) {
  180. result.Add(reader.ReadLine());
  181. }
  182.  
  183. reader.Close();
  184. response.Close();
  185. return result;
  186. }
  187. catch (Exception ex) {
  188. clsErrLog errLog = new clsErrLog("Error in clsFTPclient.DirectoryListing():" + NL + ex.Message);
  189. return result;
  190. }
  191. }
  192.  
  193. public void DownloadFile(string file, string destination) {
  194.  
  195. /* Examples of how to invoke:
  196.   *
  197.   * * sample button click_event handler follows...
  198.   * ======================================================================
  199.  
  200.   string username = "myUsername";
  201.   string password = "myPassword";
  202.   string host = "ftp://myWebsite.com";
  203.  
  204.   clsFTPclient client = new clsFTPclient(host + "/httpdocs/downloads/", username, password);
  205.   client.DownloadFile("booksOnServer.html", "downloadedToLocalDirectory.html");
  206.   }
  207.   * ===================================================================== */
  208.  
  209.  
  210. if (FileExistsAtThisURI(_remoteHost + file, _remoteUser,
  211. _remotePass)) {
  212.  
  213. try {
  214. FtpWebRequest request =
  215. (FtpWebRequest)WebRequest.Create(_remoteHost + file);
  216. request.Method = WebRequestMethods.Ftp.DownloadFile;
  217. request.Credentials =
  218. new NetworkCredential(_remoteUser, _remotePass);
  219. FtpWebResponse response =
  220. (FtpWebResponse)request.GetResponse();
  221. Stream responseStream = response.GetResponseStream();
  222. StreamReader reader = new StreamReader(responseStream);
  223.  
  224. StreamWriter writer = new StreamWriter(destination);
  225. writer.Write(reader.ReadToEnd());
  226.  
  227. writer.Close();
  228. reader.Close();
  229. response.Close();
  230. }
  231. catch (Exception ex) {
  232. clsErrLog errLogger =
  233. new clsErrLog("Error in clsFTPclient.DownloadFile()" + NL + ex.Message);
  234. }
  235. }
  236. else {
  237. clsErrLog errLogger =
  238. new clsErrLog("Error in clsFTPclient.DownloadFile(): " + NL + "The file you're attempting to download, '" +
  239. (_remoteHost + file) +
  240. "', doesn't exist on the server at the URI you specified when " +
  241. "you invoked the Download method.");
  242. }
  243. }
  244.  
  245. public bool FileExistsAtThisURI(string fullFtpFilepath, string userName,
  246. string passWord) {
  247. bool exists = true;
  248. var request =
  249. (FtpWebRequest)WebRequest.Create(fullFtpFilepath);
  250. request.Credentials =
  251. new NetworkCredential(userName, passWord);
  252. request.Method =
  253. WebRequestMethods.Ftp.GetDateTimestamp;
  254. try {
  255. FtpWebResponse response =
  256. (FtpWebResponse)request.GetResponse();
  257. }
  258. catch (WebException ex) {
  259. FtpWebResponse response = (FtpWebResponse)ex.Response;
  260. if (response.StatusCode ==
  261. FtpStatusCode.ActionNotTakenFileUnavailable) {
  262. exists = false; //Does not exist
  263. }
  264. }
  265. return exists;
  266. }
  267.  
  268. public void UploadFile(string FullPathFilename) {
  269.  
  270. /* Be sure to invoke UploadFile on an asynch thread,
  271.   * like on a backgroundWorker...
  272.  
  273.   private void backgroundWorker1_DoWork(object sender,
  274.   * System.ComponentModel.DoWorkEventArgs e) {
  275.  
  276.   string username = "my_username";
  277.   string password = "my_password";
  278.   string host = "ftp://mywebsite.com";
  279.   string myLocal = Path.GetDirectoryName(Application.ExecutablePath) +
  280.   "\\myTextFile.txt";
  281.   string myRemote = host + "/httpdocs/non_church/";
  282.   clsFTPclient client = new clsFTPclient(myRemote, username, password);
  283.   client.UploadFile(myLocal);
  284.   }
  285.   *
  286.   * ... or, rather than use a backgroundWorker...
  287.   *
  288.   * set up the same variables as above (username, password, host, myLocal, myRemote)
  289.   *
  290.   * instantiate client as shown above, and then....
  291.   *
  292.   * new System.Threading.Thread(() =>
  293.   * client.UploadFile(Path.GetDirectoryName(Application.ExecutablePath) +
  294.   "\\myTextFile.txt")).Start(); */
  295.  
  296. string filename = Path.GetFileName(FullPathFilename);
  297.  
  298. try {
  299. FtpWebRequest request =
  300. (FtpWebRequest)WebRequest.Create(_remoteHost + filename);
  301. request.Method = WebRequestMethods.Ftp.UploadFile;
  302. request.Credentials =
  303. new NetworkCredential(_remoteUser, _remotePass);
  304.  
  305. StreamReader sourceStream = new StreamReader(FullPathFilename);
  306. byte[] fileContents =
  307. Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
  308.  
  309. request.ContentLength = fileContents.Length;
  310.  
  311. Stream requestStream = request.GetRequestStream();
  312. requestStream.Write(fileContents, 0, fileContents.Length);
  313.  
  314. FtpWebResponse response = (FtpWebResponse)request.GetResponse();
  315.  
  316. response.Close();
  317. requestStream.Close();
  318. sourceStream.Close();
  319.  
  320. }
  321. catch (Exception ex) {
  322. clsErrLog errLogger =
  323. new clsErrLog("Error in clsFTPclient.UploadFile()" +
  324. NL + ex.Message);
  325. }
  326. }
  327.  
  328. #endregion
  329.  
  330. //next right-brace ends clsFTPclient
  331. }
  332.  
  333. public class clsDirDetails {
  334.  
  335. //a class to hold, in a convenient way, the details that are returned
  336. //by WebRequestMethods.Ftp.ListDirectoryDetails
  337.  
  338. public enum DirectoryDetail { IsFileInDir, IsSubdirInDir };
  339.  
  340. #region clsDirDetails_PrivateMembers
  341.  
  342. private DirectoryDetail dirMemberType; //is it a file or subdirectory?
  343. private string pathOrFilename; //path of subdir or filename if it's a file
  344. private string lastModified; //last time file got modified (applies to files only)
  345. private string unparsed; //the unparsed line that contains details
  346. private string ownerPermissions; //usually this will be rwx (read/write/execute)
  347. private bool ownerCanRead; //owner CAN or CANNOT read the specified dir/file
  348. private bool ownerCanWrite; //same as above, except WRITE rather than READ
  349. private bool ownerCanExecute; //same as above, except EXECUTE rather than WRITE
  350.  
  351. #endregion
  352.  
  353. #region clsDirDetails_Properties
  354.  
  355. //is it a file or a subdirectory?
  356. public DirectoryDetail DirMemberType {
  357. get { return dirMemberType; }
  358. set { dirMemberType = value; }
  359. }
  360.  
  361. //owner permissions
  362. public string OwnerPermissions {
  363. get { return ownerPermissions; }
  364. set { ownerPermissions = value; }
  365. }
  366.  
  367. //owner can read?
  368. public bool OwnerCanRead {
  369. get { return ownerCanRead; }
  370. set { ownerCanRead = value; }
  371. }
  372.  
  373. //owner can write?
  374. public bool OwnerCanWrite {
  375. get { return ownerCanWrite; }
  376. set { ownerCanWrite = value; }
  377. }
  378.  
  379. //owner can execute?
  380. public bool OwnerCanExecute {
  381. get { return OwnerCanExecute; }
  382. set { ownerCanExecute = value; }
  383. }
  384.  
  385. //the full path
  386. public string PathOrFilename {
  387. get { return pathOrFilename; }
  388. set { pathOrFilename = value; }
  389. }
  390.  
  391. //for files only...
  392. public string LastModified {
  393. get { return lastModified; }
  394. set { lastModified = value; }
  395. }
  396.  
  397. //the unparsed line that contains details
  398. public string Unparsed {
  399. get { return unparsed; }
  400. set {
  401. unparsed = value;
  402.  
  403. LastModified = getDateTimeString(unparsed);
  404.  
  405. //also parse out the subdir path or filename
  406. PathOrFilename = getPathOrFilename(unparsed);
  407.  
  408. //assign DirMemberType
  409. DirMemberType = getDirectoryDetail(unparsed);
  410.  
  411. //assign OwnerPermissions
  412. ownerPermissions = unparsed.Substring(1, 3);
  413. if (ownerPermissions.Contains("r")) {
  414. ownerCanRead = true; }
  415. else { ownerCanRead = false; }
  416. if (ownerPermissions.Contains("w")) {
  417. ownerCanWrite = true; }
  418. else { ownerCanWrite = false; }
  419. if (ownerPermissions.Contains("x")) {
  420. ownerCanExecute = true; }
  421. else { ownerCanExecute = false; }
  422.  
  423. //next right-brace ends set accessor of Unparsed property
  424. }
  425. //next right-brace ends Property Unparsed
  426. }
  427.  
  428. #endregion
  429.  
  430. #region clsDirDetails_Methods
  431.  
  432. clsDirDetails.DirectoryDetail getDirectoryDetail(string unparsedInfo) {
  433. if (unparsed.Substring(0, 1) == "d") {
  434. return clsDirDetails.DirectoryDetail.IsSubdirInDir;
  435. }
  436. else {
  437. return clsDirDetails.DirectoryDetail.IsFileInDir;
  438. }
  439. }
  440.  
  441. #region clsDirDetails_StringMethods
  442.  
  443. string getPathOrFilename(string unparsedInfo) {
  444. int j = unparsedInfo.LastIndexOf(' ');
  445. return unparsedInfo.Substring(j + 1, unparsedInfo.Length - j - 1);
  446. }
  447.  
  448. string getDateTimeString(string unparsedInfo) {
  449.  
  450. string result = string.Empty;
  451. int i = getIndexOfDateBeginning(unparsedInfo);
  452. if (i < 0) {
  453. clsErrLog errLogger =
  454. new clsErrLog("Error in clsDirDetails: method " +
  455. "getDateTimeString()'s sub-method getIndexOfDateBeginning() " +
  456. "returned a value of -1.");
  457. }
  458. result = unparsedInfo.Substring(i, unparsedInfo.Length - (i+1));
  459. int j = result.LastIndexOf(" ");
  460. result = result.Substring(0, j);
  461. //if, for whatever reason, we've failed to parse out a
  462. //valid DateTime, error-log it
  463. if (!objectIsDate(result)) {
  464. clsErrLog errLogger =
  465. new clsErrLog("Error in getDateTimeString() in clsFTPclient. The " +
  466. "parsed result does not appear to be a valid DateTime.");
  467. }
  468. return result;
  469. }
  470.  
  471. #endregion
  472.  
  473. #region clsDirDetails_BooleanMethods
  474.  
  475. bool objectIsDate(Object obj) {
  476. string strDate = obj.ToString();
  477. try {
  478. DateTime dt = DateTime.Parse(strDate);
  479. if (dt != DateTime.MinValue && dt != DateTime.MaxValue)
  480. return true;
  481. return false;
  482. }
  483. catch {
  484. return false;
  485. }
  486. }
  487.  
  488. #endregion
  489.  
  490. #region clsDirDetails_IntegerMethods
  491.  
  492. int getIndexOfFirstAlphabeticCharacter(string source) {
  493. int i = -1;
  494. foreach (char c in source) {
  495. i++;
  496. if (Char.IsLetter(c)) { return i; }
  497. }
  498. return i;
  499. }
  500.  
  501. int getIndexOfDateBeginning(string unparsedInfo) {
  502. int i = -1;
  503.  
  504. i = unparsedInfo.IndexOf("Jan");
  505. if (i > -1) { return i; }
  506.  
  507. i = unparsedInfo.IndexOf("Feb");
  508. if (i > -1) { return i; }
  509.  
  510. i = unparsedInfo.IndexOf("Mar");
  511. if (i > -1) { return i; }
  512.  
  513. i = unparsedInfo.IndexOf("Apr");
  514. if (i > -1) { return i; }
  515.  
  516. i = unparsedInfo.IndexOf("May");
  517. if (i > -1) { return i; }
  518.  
  519. i = unparsedInfo.IndexOf("Jun");
  520. if (i > -1) { return i; }
  521.  
  522. i = unparsedInfo.IndexOf("Jul");
  523. if (i > -1) { return i; }
  524.  
  525. i = unparsedInfo.IndexOf("Aug");
  526. if (i > -1) { return i; }
  527.  
  528. i = unparsedInfo.IndexOf("Sep");
  529. if (i > -1) { return i; }
  530.  
  531. i = unparsedInfo.IndexOf("Oct");
  532. if (i > -1) { return i; }
  533.  
  534. i = unparsedInfo.IndexOf("Nov");
  535. if (i > -1) { return i; }
  536.  
  537. i = unparsedInfo.IndexOf("Dec");
  538. if (i > -1) { return i; }
  539.  
  540. return i;
  541. }
  542.  
  543. #endregion
  544.  
  545. #endregion
  546.  
  547. //next right-brace ends clsDirDetails
  548. }
  549.  
  550. //next right-brace ends namespace Kyrathasoft.NetUtilities.FTPclient
  551. }

Report this snippet  

You need to login to post a comment.