2016-05-11 11 views
1

Ich hatte eine C# Hausaufgaben, die ich einen Download-Manager machen muss, habe ich bereits abgeschlossen.C# automatisch Dateispeicherort nach dem Download von FTP-Server

Dies ist mein Code:

using System; 
    using System.Collections.Generic; 
    using System.ComponentModel; 
    using System.Data; 
    using System.Drawing; 
    using System.Text; 
    using System.Windows.Forms; 

    using System.IO; 
    using System.Net; 

    namespace DownloadDataFTP 
    { 
    public partial class ftpForm : Form 
{ 
    public ftpForm() 
    { 
     InitializeComponent(); 
    } 

    private byte[] downloadedData; 

    //Connects to the FTP server and downloads the file 
    private void downloadFile(string FTPAddress, string filename, string username, string password) 
    { 
     downloadedData = new byte[0]; 

     try 
     { 
      //Create FTP request 
      //Note: format is ftp://server.com/file.ext 
      FtpWebRequest request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest; 


      //Get the file size first (for progress bar) 
      request.Method = WebRequestMethods.Ftp.GetFileSize; 
      request.Credentials = new NetworkCredential(username, password); 
      request.UsePassive = true; 
      request.UseBinary = true; 
      request.KeepAlive = true; //don't close the connection 

      int dataLength = (int)request.GetResponse().ContentLength; 


      //Now get the actual data 
      request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest; 

      request.Method = WebRequestMethods.Ftp.DownloadFile; 
      request.Credentials = new NetworkCredential(username, password); 
      request.UsePassive = true; 
      request.UseBinary = true; 
      request.KeepAlive = false; //close the connection when done 

      //Set up progress bar 
      progressBar1.Value = 0; 
      progressBar1.Maximum = dataLength; 
      lbProgress.Text = "0/" + dataLength.ToString(); 

      //Streams 
      FtpWebResponse response = request.GetResponse() as FtpWebResponse; 
      Stream reader = response.GetResponseStream(); 

      //Download to memory 
      //Note: adjust the streams here to download directly to the hard drive 
      MemoryStream memStream = new MemoryStream(); 
      byte[] buffer = new byte[1024]; //downloads in chuncks 

      while (true) 
      { 
       Application.DoEvents(); //prevent application from crashing 

       //Try to read the data 
       int bytesRead = reader.Read(buffer, 0, buffer.Length); 

       if (bytesRead == 0) 
       { 
        //Nothing was read, finished downloading 
        progressBar1.Value = progressBar1.Maximum; 
        lbProgress.Text = dataLength.ToString() + "/" + dataLength.ToString(); 

        Application.DoEvents(); 
        break; 
       } 
       else 
       { 
        //Write the downloaded data 
        memStream.Write(buffer, 0, bytesRead); 

        //Update the progress bar 
        if (progressBar1.Value + bytesRead <= progressBar1.Maximum) 
        { 
         progressBar1.Value += bytesRead; 
         lbProgress.Text = progressBar1.Value.ToString() + "/" + dataLength.ToString(); 

         progressBar1.Refresh(); 
         Application.DoEvents(); 
        } 
       } 
      } 

      //Convert the downloaded stream to a byte array 
      downloadedData = memStream.ToArray(); 

      //Clean up 
      reader.Close(); 
      memStream.Close(); 
      response.Close(); 

      MessageBox.Show("Downloaded Successfully"); 
     } 
     catch (Exception) 
     { 
      MessageBox.Show("Connection error. Please try again!"); 
     } 

     txtData.Text = downloadedData.Length.ToString(); 
     this.Text = "Group 10 Download and Upload Manager"; 

     username = string.Empty; 
     password = string.Empty; 
    } 

    //Upload file via FTP 
    private void Upload(string FTPAddress, string filePath, string username, string password) 
    { 
     //Create FTP request 
     FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPAddress + "/" + Path.GetFileName(filePath)); 

     request.Method = WebRequestMethods.Ftp.UploadFile; 
     request.Credentials = new NetworkCredential(username, password); 
     request.UsePassive = true; 
     request.UseBinary = true; 
     request.KeepAlive = false; 

     //Load the file 
     FileStream stream = File.OpenRead(filePath); 
     byte[] buffer = new byte[stream.Length]; 

     stream.Read(buffer, 0, buffer.Length); 
     stream.Close(); 

     //Upload file 
     Stream reqStream = request.GetRequestStream(); 
     reqStream.Write(buffer, 0, buffer.Length); 
     reqStream.Close(); 

     MessageBox.Show("Uploaded Successfully"); 
    } 

    //get file size for downloading 
    private void FileSize_down(string FTPAddress, string filename, string username, string password) 
    { 
     FtpWebRequest request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest; 
     request.Method = WebRequestMethods.Ftp.GetFileSize; 

     request.Credentials = new NetworkCredential(username, password); 
     request.UsePassive = true; 
     request.UseBinary = true; 
     request.KeepAlive = false; 

     long dataLength = (long)request.GetResponse().ContentLength; 
     sizeFile.Text = dataLength.ToString(); 
    } 



    //Connects to the FTP server and request the list of available files 
    private void getFileList(string FTPAddress, string username, string password) 
    { 
     List<string> files = new List<string>(); 

     try 
     { 
      //Create FTP request 
      FtpWebRequest request = FtpWebRequest.Create(FTPAddress) as FtpWebRequest; 

      request.Method = WebRequestMethods.Ftp.ListDirectory; 
      request.Credentials = new NetworkCredential(username, password); 
      request.UsePassive = true; 
      request.UseBinary = true; 
      request.KeepAlive = false; 


      FtpWebResponse response = request.GetResponse() as FtpWebResponse; 
      Stream responseStream = response.GetResponseStream(); 
      StreamReader reader = new StreamReader(responseStream); 

      while (!reader.EndOfStream) 
      { 
       Application.DoEvents(); 
       files.Add(reader.ReadLine()); 
      } 

      //Clean-up 
      reader.Close(); 
      responseStream.Close(); //redundant 
      response.Close(); 
     } 
     catch (Exception) 
     { 
      MessageBox.Show("There was an error connecting to the FTP Server"); 
     } 

     username = string.Empty; 
     password = string.Empty; 

     this.Text = "Group 10 Download and Upload Manager"; //Back to normal title 

     //If the list was successfully received, display it to the user 
     //through a dialog 
     if (files.Count != 0) 
     { 
      listDialogForm dialog = new listDialogForm(files); 
      if (dialog.ShowDialog() == DialogResult.OK) 
      { 
       //Update the File Name field 
       txtFileName.Text = dialog.ChosenFile; 
      } 
     } 
    } 

    //Make sure the FTP server address has ftp:// at the beginning 
    private void txtFTPAddress_Leave(object sender, EventArgs e) 
    { 
     if (!txtFTPAddress.Text.StartsWith("ftp://")) 
      txtFTPAddress.Text = "ftp://" + txtFTPAddress.Text; 
    } 

    private void btnGetList_Click(object sender, EventArgs e) 
    { 
     if (txtFTPAddress.Text != "ftp://" && txtFTPAddress.Text != string.Empty) 
      getFileList(txtFTPAddress.Text, txtUsername.Text, txtPassword.Text); 
     else 
      MessageBox.Show("Please enter a FTP address"); 
    } 

    //Download button 
    private void btnDownload_Click(object sender, EventArgs e) 
    { 
     if (txtFTPAddress.Text != "ftp://" && txtFTPAddress.Text != string.Empty) 
      if (txtFileName.Text != string.Empty) 
      { 
       downloadFile(txtFTPAddress.Text, txtFileName.Text, txtUsername.Text, txtPassword.Text); 

       saveFile1.FileName = txtFileName.Text; 
      } 
      else 
       MessageBox.Show("Please enter a file name or click the Get File List button"); 
     else 
      MessageBox.Show("Please enter a FTP address"); 
    } 

    //Save Button 
    private void btnSave_Click(object sender, EventArgs e) 
    { 
     if (downloadedData != null && downloadedData.Length != 0) 
     { 
      if (saveFile1.ShowDialog() == DialogResult.OK) 
      { 
       this.Text = "Saving Data..."; 
       Application.DoEvents(); 

       //Write the bytes to a file 
       FileStream newFile = new FileStream(saveFile1.FileName, FileMode.Create); 
       newFile.Write(downloadedData, 0, downloadedData.Length); 
       newFile.Close(); 

       this.Text = "Download Data"; 
       MessageBox.Show("Saved Successfully"); 
      } 
     } 
     else 
      MessageBox.Show("Please download first!"); 
    } 

    //GetFile button 
    private void button1_Click(object sender, EventArgs e) 
    { 
     FileSize_down(txtFTPAddress.Text, txtFileName.Text, txtUsername.Text, txtPassword.Text); 
    } 



    } 
    } 

Allerdings gibt es immer noch eine Anforderung, dass ich nicht wusste, wie abgeschlossen. Das heißt, wenn der Download abgeschlossen ist, wird der Speicherort der Datei automatisch mit dem Windows Explorer geöffnet.

Kann mir jemand helfen?

+0

Verwenden Process.Start (""); –

+0

Mögliches Duplikat von [Wie kann ich den Windows Explorer von einer WPF App aus in ein bestimmtes Verzeichnis öffnen?] (Http://stackoverflow.com/questions/1746079/how-can-i-open-windows-explorer-to-a -irgendein-Verzeichnis-von-innerhalb-a-wpf-app) –

+0

Ich weiß nicht, aber ist Process.Start verwendet, um Datei von einem bestimmten Ort zu öffnen? Mein Programm ist nach dem Download Sie wählen, um die Datei an einem beliebigen Ort zu speichern, und dann nach dem Speichern der Datei automatisch geöffnet. –

Antwort

0

In Ihrem btnSave_Click Fall versuchen, so etwas wie dies nach der Linie MessageBox.Show("Saved Successfully");

string dir = Path.GetDirectoryName(saveFile1.FileName); 

System.Diagnostic.Process.Start("explorer", dir); 
+0

Es hat funktioniert. Ich danke dir sehr. –

Verwandte Themen