1

我用这种方法下载了一个文件:

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);
                        }
                    }
                }

仍然得到错误....

4

2 回答 2

4
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);
        }
    }
}
于 2013-04-11T14:47:32.300 回答
0

试试这种方式:

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();
于 2013-04-11T14:53:15.983 回答