c# - 正在保存上传的文件 - 进程无法访问

标签 c# upload permissions

我有以下函数来处理上传的图片。

它在第一次尝试时工作正常(在重新启动 IIS 之后),但在第二次尝试时我总是得到

The process cannot access the file because it is being used by another process

现在,我明白 IIS 以某种方式使文件保持打开状态,但如果我有,为什么会发生这种情况

newFile.Flush();
newFile.Close();
newFile.Dispose();

这里是完整的函数:

private void SaveFile(HttpPostedFile file, string path)
{
    Int32 fileLength = file.ContentLength;
    string fileName = file.FileName;
    byte[] buffer = new byte[fileLength];
    file.InputStream.Read(buffer, 0, fileLength);

    FileStream newFile = new FileStream(path, FileMode.Create, FileAccess.Write);

    try
    {
        newFile.Write(buffer, 0, buffer.Length);
    }
    catch { }
    finally
    {
        newFile.Flush();
        newFile.Close();
        newFile.Dispose();
    }
}

更新:
经过几次检查后,我确定除了 IIS 进程 w3wp.exe 之外没有其他任何东西锁定文件。

最佳答案

必须有其他原因使文件保持打开状态 - 或者可能在第一次调用返回之前进行了第二次调用(在单独的线程上)。

顺便说一下,你最好这样写代码:

private void SaveFile(HttpPostedFile file, string path)
{
    Int32 fileLength = file.ContentLength;
    string fileName = file.FileName;
    byte[] buffer = new byte[fileLength];
    file.InputStream.Read(buffer, 0, fileLength);

    using (FileStream newFile = new FileStream(path, FileMode.Create, FileAccess.Write))
    {
        newFile.Write(buffer, 0, buffer.Length);
    }
}

关于c# - 正在保存上传的文件 - 进程无法访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11393316/

相关文章:

android - 图像是从画廊上传的,而不是通过 webView 从相机上传的

php - 上传文件时保留最后修改日期

c# - IronPdf 打印到页边距

c# - 可以在 Xamarin Forms 中使用的汉堡包/抽屉下拉菜单?

PHP上传图片

c# - 图形 API - 权限不足,无法完成操作

php - 如何授予 Composer 在 var/www/html 中创建文件夹的权限

android - 由于缺少权限请求,应用程序崩溃

c# - 如何使用 Microsoft Graph sdk 通过电子邮件地址从 Active Directory 获取用户信息

使用 AddRange 的 C# 种子私有(private)成员