我正在創建一個接受文件流作爲參數而不是字符串的重載方法,並且我想確保我做得正確,特別是我對文件流不是很熟悉。用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;
}
是什麼讓你覺得這是錯誤的方式?這是關於FileStream或重載的問題嗎? – tnw
這是[CodeReview](http://codereview.stackexchange.com/)的很好的候選人。如果調用者傳入'FileStream',那麼我會假設他們會希望你輸出數據到'FileStream'。更不用說'FileStream'已經有了資源的句柄。 – Romoku
@tnw關於FileStream – Masriyah