下载文件并同时读取
本文关键字:读取 文件 下载 | 更新日期: 2023-09-27 18:08:34
我用这个方法下载一个文件:
WebClient WC = new WebClient();
WC.DownloadFile(url, filePath);
我想在读取文件的同时使用
var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
但我总是得到:
The process cannot access the file 'filePath' because it is being used by another process.
可以同时下载和阅读吗?
<标题>编辑我现在下载文件:
var req = (HttpWebRequest)HttpWebRequest.Create(url);
var fileStream = new FileStream(filePath,
FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
using (var resp = req.GetResponse())
{
using (var stream = resp.GetResponseStream())
{
byte[] buffer = new byte[0x10000];
int len;
while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
{
fileStream.Write(buffer, 0, len);
}
}
}
仍然得到错误....
标题>var req = (HttpWebRequest)HttpWebRequest.Create(url);
using (var resp = req.GetResponse())
{
using (var stream = resp.GetResponseStream())
{
byte[] buffer = new byte[0x10000];
int len;
while ((len = stream.Read(buffer, 0, buffer.Length))>0)
{
//Do with the content whatever you want
// ***YOUR CODE***
fileStream.Write(buffer, 0, len);
}
}
}
试试:
HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://www.domain.com/file.txt");
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
var stream = response.GetResponseStream();
byte[] buffer = new byte[8192];
int bytesRead = 0;
while ((bytesRead = stream.Read(buffer, 0, 8192)) > 0)
{
// handle your raw data
// you needed raw data = buffer[0 to bytesRead - 1]
}
stream.Close();
response.Close();