文件复制锁定文件,因此数据无法写入

问题描述 投票:0回答:1

我有几个文件模板存储在 C:\Webs\web-n-rsgpsd\Administration\Templates 中,作为已部署 Web 应用程序的一部分。然后应将数据导出到文件的副本(从 Templates 复制到 ExtractOutput),但每次运行时,应用程序都会出现 500 - 内部服务器错误,并且根据服务器上的应用程序日志:
该进程无法访问文件“C:\Webs\web-n-rsgpsd\Administration\ExtractOutput\AskDataExtractTemplate.xlsx”,因为该文件正在被另一个进程使用。0
因此,虽然文件被复制(并且可以在 ExtractOutput 文件夹中看到),但无法将数据写入其中。如果我尝试从 ExtractOutput 文件夹中打开该文件,它会说该文件已被“另一个用户”锁定以进行编辑'.
这是创建模板副本的代码:

    private FileInfo GetExportFilename()
    {
        const string templateFilename = "AskDataExtractTemplate.xlsx";
        var templateFileInfo = new FileInfo(Server.MapPath($"~/Administration/Templates/{templateFilename}"));
        var temporaryFile = Server.MapPath($"~/Administration/ExtractOutput/{templateFilename}");
        templateFileInfo.CopyTo(temporaryFile, true);
        templateFileInfo = new FileInfo(temporaryFile) { IsReadOnly = false };
        return templateFileInfo;
    }

这是用于导出数据的连接字符串:
连接字符串:Provider=Microsoft.ACE.OLEDB.12.0;数据源=C:\Webs\web-n-rsgpsd\Administration\ExtractOutput\ASKDataExtractTemplate.xlsx;扩展属性='Excel 12.0 Xml;HDR=YES'
谁能解释一下为什么文件被锁定,因此数据无法写入其中?

c# webserver file-copying
1个回答
0
投票

你的方法

templateFileInfo.CopyTo(temporaryFile, true);

使用:

FileSystem.CopyFile(FullPath, destinationPath, overwrite);
,根据此answer锁定文件并引发异常。

如果不想锁定文件,您应该使用不同的方法来复制文件。

© www.soinside.com 2019 - 2024. All rights reserved.