我正在创建一个接受文件流作为参数而不是字符串的重载方法,并且我想确保我以正确的方式特别是我对文件流不太熟悉。
原始方法:
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;
}