流或文件未关闭

时间:2012-05-20 07:00:05

标签: c# asp.net-mvc-3 file stream

我有他的代码

    HttpPostedFileBase files = Request.Files[0];
    Stream fileStream = files.InputStream;

    using (Stream file = System.IO.File.OpenWrite(originalImage))
    {
        StreamUtil.CopyStream(fileStream, file);
        file.Close();
        fileStream.close();
        fileStream.dispose();
    }

    // here is CopyStream method

    public static void CopyStream(Stream input, Stream output)
    {
        var buffer = new byte[8*1024];
        int len;
        while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, len);
        }
    }

当我尝试两次写同一个文件时,我得到了

The process cannot access the file \u0027D:FILENAME because it is being used by another process

我如何关闭它?所以一旦写完请求,它就会被关闭?

1 个答案:

答案 0 :(得分:0)

我想把它写成评论,但不清楚:

尝试做这样的事情:

MemoryStream fileStream = new MemoryStream();

fileStream.WriteByte(04);

using (Stream file = System.IO.File.OpenWrite(originalImage))
{
    CopyStream(fileStream, file);
}

using (Stream file = System.IO.File.OpenWrite(originalImage))
{
    CopyStream(fileStream, file);
}

你在使用第二行时会得到同样的错误吗?