2013-07-23 20 views
0

我正在創建一個接受文件流作爲參數而不是字符串的重載方法,並且我想確保我做得正確,特別是我對文件流不是很熟悉。用filestream創建一個超載的方法

原始的方法:

public bool DownloadFile(string getFile, string downloadToPath) 
     { 
      if (File.Exists(downloadToPath)) 
       File.Delete(downloadToPath); 

      //we are not downloading collections, so return false 
      if (_resource.IsCollection(fileToRetrieve)) 
       return false; 

      _resource.Download(getFile, downloadToPath); 

      return File.Exists(downloadToPath); 
     } 

重載方法:

public bool DownloadFile(string getFile, string downloadToPath) 
    { 
     using (FileStream file = new FileStream(getFile, FileMode.Open, FileAccess.Read)) 
     { 
      string filePath = file.Name; 
      string filePathName = Path.GetFileName(filePath); 

      byte[] bytes = new byte[file.Length]; 
      int numBytesToRead = (int)file.Length; 
      int numBytesRead = 0; 

      while (numBytesToRead > 0) 
      { 
       //If file exists, the read will return anything from 0 to numBytesToRead 
       int fileBytes = file.Read(bytes, numBytesRead, numBytesToRead); 

       //Break when the end of the file has been reached 
       if (fileBytes == 0) 
        break; 

       numBytesRead += fileBytes; 
       numBytesToRead -= fileBytes; 
      } 
      numBytesToRead = bytes.Length; 

      //Write the byte array to the new file stream 
      using (FileStream localPathStream = new FileStream(downloadToPath, FileMode.Create, FileAccess.Write)) 
      { 
       localPathStream.Write(bytes, 0, numBytesToRead); 
      } 
     } 
     return false; 
    } 
+0

是什麼讓你覺得這是錯誤的方式?這是關於FileStream或重載的問題嗎? – tnw

+3

這是[CodeReview](http://codereview.stackexchange.com/)的很好的候選人。如果調用者傳入'FileStream',那麼我會假設他們會希望你輸出數據到'FileStream'。更不用說'FileStream'已經有了資源的句柄。 – Romoku

+0

@tnw關於FileStream – Masriyah

回答

0

使用Stream.CopyTo可以簡化您的方法。你的方法首先將所有的字節讀入內存,這對於大文件來說是不可取的。

File.OpenRead類似於FileMode.ReadFileAccess.Read標誌。

File.OpenWrite類似於FileMode.OpenOrCreateFileAccess.Write

public bool DownloadFile(string getFile, string downloadToPath) 
{ 
    if(string.IsNullOrWhiteSpace(getFile) || string.IsNullOrWhiteSpace(downloadToPath)) return false; 

    try 
    { 
     using(var readStream = File.OpenRead(getFile)) 
     using(var writeStream = File.OpenWrite(downloadToPath)) 
     { 
      readStream.CopyTo(writeStream, 1024); 
     } 
    } 
    catch(Exception e) 
    { 
     // log exception or rethrow 
     return false; 
    } 

    return true; 
} 
0

它可以在你的情況下工作,但請你注意的是,通過definnition流,所以FileStream也可以不是磁盤上的文件,而是一些流數據或一些無限數據流(例如推文...)。

通過和fileName一起離開paameter,您可以在文件中詳細說明你的擴展方法。

所以我建議不要像這樣增加過載。

+0

我想創建一個DownloadFile方法,但使用'FileStream'參數而不是字符串。最終我將使用'FileStream'的方法,而不是使用字符串的方法,但我現在已經將它們用於測試 – Masriyah

+0

我改變了上面的方法,請您仔細查看並分享任何輸入 – Masriyah