0

我打开一个具有写权限的文件。但是当我想再次打开一个同名的文件时,我得到一个异常。这里的代码:

// 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 应该可以工作,但事实并非如此。任何想法?

4

2 回答 2

0

在写入文件之前,您是否尝试关闭以前的 Stream:

                myFile.InputStream.Flush();
                myFile.InputStream.Close();

              // Write data into a file
                WriteToFile(Server.MapPath("Files//" + Constantes.strFilenameMdl), ref myData);
于 2013-09-06T22:10:53.780 回答
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.ReadWriteFileStream

    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);
        }
    }
于 2013-09-06T22:25:27.847 回答