我打开一个具有写入权限的文件。但是,当我想再打开一个同名文件时,我得到一个例外。代码如下:
// Check to see if file was uploaded
if (FileMdl.PostedFile != null)
{
// Get a reference to PostedFile object
HttpPostedFile myFile = FileMdl.PostedFile;
// Get size of uploaded file
int nFileLen = myFile.ContentLength;
// make sure the size of the file is > 0
if (nFileLen > 0)
{
// Allocate a buffer for reading of the file
byte[] myData = new byte[nFileLen];
// Read uploaded file from the Stream
myFile.InputStream.Read(myData, 0, nFileLen);
// Create a name for the file to store
Constantes.strFilenameMdl = Path.GetFileName(myFile.FileName);
// Write data into a file
WriteToFile(Server.MapPath("Files//" + Constantes.strFilenameMdl), ref myData);
myFile.InputStream.Flush();
myFile.InputStream.Close();
}
}
private void WriteToFile(string strPath, ref byte[] Buffer)
{
// Create a file
FileStream newFile = new FileStream(strPath, FileMode.Create,FileAccess.ReadWrite,FileShare.ReadWrite);
// Write data to the file
newFile.Write(Buffer, 0, Buffer.Length);
// Close file
newFile.Flush();
newFile.Close();
newFile.Dispose();
}
据说Flush或Close或Dispose应该可以工作,但不是这样。有什么想法吗?
答案 0 :(得分:0)
在写入文件之前,您曾尝试关闭上一个Stream:
myFile.InputStream.Flush();
myFile.InputStream.Close();
// Write data into a file
WriteToFile(Server.MapPath("Files//" + Constantes.strFilenameMdl), ref myData);
答案 1 :(得分:0)
尝试像这样使用using
语句:
private void WriteToFile(string strPath, ref byte[] Buffer)
{
// Create a file
using (FileStream newFile = new FileStream(strPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
// Write data to the file
newFile.Write(Buffer, 0, Buffer.Length);
}
}
详情请见:http://msdn.microsoft.com/en-us/library/vstudio/yh598w02(v=vs.100).aspx
注意:您还可以通过从ref
语句中删除输入参数和FileShare.ReadWrite
参数中的FileStream
键来简化代码,如下所示:
private void WriteToFile(string strPath, byte[] Buffer)
{
// Create a file
using (FileStream newFile = new FileStream(strPath, FileMode.Create, FileAccess.ReadWrite))
{
// Write data to the file
newFile.Write(Buffer, 0, Buffer.Length);
}
}