下载文件并在同一时间阅读

时间:2013-04-11 14:37:22

标签: c# .net

我用这种方法下载文件:

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

仍然得到错误....

2 个答案:

答案 0 :(得分: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);
        }
    }
}

答案 1 :(得分: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();