我有以下函数来处理上传的图片。
它在第一次尝试时工作正常(在重新启动 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/