覆盖时文件被锁定

时间:2013-12-20 13:26:40

标签: c# file filestream fileinfo filelock

标题解释了一小部分,让我解释两个场景。场景1引发错误,场景2就像魅力一样。

场景1:

我使用下面的方法检出文档,当文档保存到已经是具有该名称的文件被覆盖的位置时,但令人惊讶的是它还因某些原因锁定了文件:

public bool SaveDocument(int bestandsId, string fileName, string path)
{
    //Initialize the Sql Query
    var sql = "SELECT DATA FROM Documenten WHERE BESTAND_ID = " + bestandsId;
    //Initialize SqlConnection
    var connection = new SqlConnection(Instellingen.Instance.DmsConnectionString);
    //Initialize SqlCommand
    var command = new SqlCommand(sql, connection);

    try
    {
        //Open Connection
        connection.Open();
        //Fill 'data' from command.ExecuteScalar()
        var data = (byte[]) command.ExecuteScalar();
        //Write 'data' to file.
        File.WriteAllBytes(path + @"\" + fileName, data);
        //Return true if no exceptions are raised.
        return true;
    }
    catch (Exception ex)
    {
        //Initialize Dms Exception
        var dmsEx = new DmsException(ex);
        //Write Dms Exception to Log File.
        DmsException.WriteErrorsToLog(dmsEx);
        //Return false, because something went wrong...
        return false;
    }
    finally
    {
        //Close Sql Connection
        connection.Close();
    }
}

该方法运行顺利。没有问题发生。但是当我使用下面的方法检查文档时,我得到了异常

Exception

场景2:

当我使用SaveDocument方法将文档保存到没有同名文件的位置时,该文件是新创建的,可以编辑或者您想要做什么用它。

使用方案2 工作正常。文档已准备好再次签入,而不会收到错误,如上图所示。

请求代码:@CodeCaster

--------------------------------- BEGIN EDIT ------------ ---------------------

    public static bool InsertDocument(Document document)
    {
        try
        {
            //Exception is thrown when Initializing the FileStream
            var fileStream = new FileStream(document.Fileinfo.FullName, FileMode.Open, FileAccess.Read); 

            var binaryReader = new BinaryReader(fileStream);
            var totalNumberOfBytes = new FileInfo(document.Fileinfo.FullName).Length;
            var data = binaryReader.ReadBytes((Int32) totalNumberOfBytes);

            fileStream.Close();
            fileStream.Dispose();
            binaryReader.Close();
            binaryReader.Dispose();

            var pdftext = string.Empty;
            try
            {
                if (document.DocumentType == ".pdf")
                {
                    var reader = new PdfReader(document.Fileinfo.FullName);
                    var text = string.Empty;
                    for (var page = 1; page <= reader.NumberOfPages; page++)
                    {
                        text += PdfTextExtractor.GetTextFromPage(reader, page);
                    }
                    reader.Close();
                    pdftext = text;
                }
            }
            catch (Exception ex)
            {
                var dmsEx = new DmsException(ex);
                DmsException.WriteErrorsToLog(dmsEx);
            }


            return InsertIntoDatabase(document.BestandsNaam, document.Eigenaar, document.Omschrijving,
                                      document.DatumToevoeg.ToString(), document.DatumIncheck.ToString(),
                                      document.DatumUitcheck.ToString(), document.UitgechecktDoor,
                                      document.DocumentType, data, pdftext, document.Versie, document.Medewerker,
                                      document.DossierNummer, document.PersonalFolderId.ToString(),
                                      document.DossierFolderId, -1, document.DocumentProgres,
                                      document.OriBestandId.ToString(), 0);
        }
        catch (Exception ex)
        {
            var dmsEx = new DmsException("Fout bij inlezen voor toevoeging van nieuw document",
                                         "Klasse Document (InsertDocument)", ex);
            ExceptionLogger.LogError(dmsEx);

            return false;
        }
    }

--------------------------------- END EDIT ------------ ---------------------

我的问题:

  1. 文件被覆盖时被锁定的原因是什么?
  2. 如何防止这种情况发生?
  3. 我可以设置某种功能或参数,以免被锁定吗?
  4. 使用名为“Unlocker”的工具我设法看到哪个程序锁定了文件, 和YES - &gt; DMS.exe是我的应用程序....... enter image description here

1 个答案:

答案 0 :(得分:-2)

using(var stream = File.Create(newPath)){}
File.WriteAllBytes(newPath, item.File);

使用StreamWriter

using (FileStream fs = File.Create(newPath))
{
    fs.Write(item.File, 0, item.File.Length);
}

或者:

File.WriteAllBytes(newPath, item.File);

参考:"The process cannot access the file because it is being used by another process" with Images