【发布时间】:2016-10-20 09:20:40
【问题描述】:
我正在编写一个使用 MEF 加载程序集的 WinForms 程序。这些程序集与可执行文件不在同一文件夹中。 由于我需要执行一些文件维护,因此在加载实际的 WinForm 之前,我在文件 Program.cs 中实现了一些代码,因此程序不会加载文件(即使是程序集)(或者不应该加载)。
我正在执行两个操作: - 将文件夹从一个位置移动到另一个位置 - 从存档中解压缩文件并覆盖移动文件夹中的 dll 文件(如果存档中的文件比移动的文件新)
问题是移动文件夹后,其中的文件被锁定,无法覆盖。我还尝试通过在移动完成后处理文件来逐个移动文件。
谁能解释一下为什么文件被阻止以及如何避免这种情况
谢谢
private static void InitializePluginsFolder()
{
if (!Directory.Exists(Paths.PluginsPath))
{
Directory.CreateDirectory(Paths.PluginsPath);
}
// Find archive that contains plugins to deploy
var assembly = Assembly.GetExecutingAssembly();
if (assembly.Location == null)
{
throw new NullReferenceException("Executing assembly is null!");
}
var currentDirectory = new FileInfo(assembly.Location).DirectoryName;
if (currentDirectory == null)
{
throw new NullReferenceException("Current folder is null!");
}
// Check if previous installation contains a "Plugins" folder
var currentPluginsPath = Path.Combine(currentDirectory, "Plugins");
if (Directory.Exists(currentPluginsPath))
{
foreach (FileInfo fi in new DirectoryInfo(currentPluginsPath).GetFiles())
{
using (FileStream sourceStream = new FileStream(fi.FullName, FileMode.Open))
{
using (FileStream destStream = new FileStream(Path.Combine(Paths.PluginsPath, fi.Name), FileMode.Create))
{
destStream.Lock(0, sourceStream.Length);
sourceStream.CopyTo(destStream);
}
}
}
Directory.Delete(currentPluginsPath, true);
}
// Then updates plugins with latest version of plugins (zipped)
var pluginsZipFilePath = Path.Combine(currentDirectory, "Plugins.zip");
// Extract content of plugins archive to a temporary folder
var tempPath = string.Format("{0}_Temp", Paths.PluginsPath);
if (Directory.Exists(tempPath))
{
Directory.Delete(tempPath, true);
}
ZipFile.ExtractToDirectory(pluginsZipFilePath, tempPath);
// Moves all plugins to appropriate folder if version is greater
// to the version in place
foreach (var fi in new DirectoryInfo(tempPath).GetFiles())
{
if (fi.Extension.ToLower() != ".dll")
{
continue;
}
var targetFile = Path.Combine(Paths.PluginsPath, fi.Name);
if (File.Exists(targetFile))
{
if (fi.GetAssemblyVersion() > new FileInfo(targetFile).GetAssemblyVersion())
{
// If version to deploy is newer than current version
// Delete current version and copy the new one
// FAILS HERE
File.Copy(fi.FullName, targetFile, true);
}
}
else
{
File.Move(fi.FullName, targetFile);
}
}
// Delete temporary folder
Directory.Delete(tempPath, true);
}
【问题讨论】:
-
请分享您的代码。
-
遗憾的是,我们甚至无法从中推测。
-
对不起,我不想放很多代码,但我想它肯定会有所帮助。该方法是 Main 方法上调用的第一个方法
-
你能确认你的程序正在生成锁吗?即运行一个程序来创建,另一个程序来提取/移动?您遇到了什么错误?
-
与您的问题无关,但您不需要执行
if (!Directory.Exists(...)) { Directory.CreateDirectory(...); }组合。如果一个目录已经存在并且你调用 CreateDirectory 不会抛出错误。
标签: c# file mef filestream locked