【问题标题】:File Still Locked Despite putting StreamReader in Using尽管使用 StreamReader,文件仍然被锁定
【发布时间】:2015-07-14 12:40:11
【问题描述】:

我的程序会遍历文件夹中的所有文件,读取它们,并且在不更改它们的信息的情况下将它们以不同的名称移动到另一个位置。但是我不能使用File.Move 方法,因为我得到了以下IOException

进程无法访问该文件,因为它正被另一个进程使用 过程。

这就是我读取文件并将其所有行添加到 List<string> 的方式:

List<string> lines = null;
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (var sr = new StreamReader(fs, Encoding.Default))
    {
        lines = new List<string>();
        while (!sr.EndOfStream)
            lines.Add(sr.ReadLine());
    }

这是我用来移动文件的函数:

public static bool ArchiveFile(string filePath, string archiveFolderLocation)
{
    if (!Directory.Exists(archiveFolderLocation))
        Directory.CreateDirectory(archiveFolderLocation);
    try
    {
        string timestamp = string.Format("{0:yyyy-MM-dd HHmmss}", DateTime.Now);
        string newFileName = Path.GetFileNameWithoutExtension(filePath) + " " + timestamp;
        string destination = string.Format("{0}\\{1}{2}", archiveFolderLocation, newFileName, Path.GetExtension(filePath));
        File.Move(filePath, destination);
        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

我认为使用using 语句应该是垃圾收集并在使用后释放文件。如何释放文件以便移动它以及为什么我的文件保持锁定状态?

已解决:

知道了。在这两个调用之间的某个地方,我打开了一个 TextReaderobject 而不处置它。

【问题讨论】:

  • 代码sn-ps是怎么链接的?扔到哪里去了?
  • @AmitKumarGhosh 上面的 sn-p 首先运行,然后是 ArchiveFile 方法。异常发生在ArchiveFile 方法的File.Move 行中。
  • 您确定该文件没有在其他地方使用吗? using 应该可以工作。但问题出在其他地方
  • 您是否使用多线程来移动文件?并行任务还是等待任务?
  • @M.kazemAkhgary 明白了。在这两个调用之间的某个地方,我打开了一个 TextReader 对象而不释放它。

标签: c# file io streamreader


【解决方案1】:

我认为使用 using 语句应该是垃圾收集和 使用后释放文件。我怎样才能释放文件,以便我可以 移动它,为什么我的文件保持锁定状态?

不是真的。 using 语句不过是:

try { var resource = new SomeResource(); } 

finally { resource.Dispose(); // which is not GC.Collect(); }

它工作正常,所以看起来你的文件是从代码中的其他地方打开的......

附: 顺便说一句,你可以这样做:

List&lt;string&gt; lines = File.ReadAllLines().ToList();

【讨论】:

    【解决方案2】:

    您可以使用:

    string dpath = "D:\\Destination\\";
                string spath = "D:\\Source";
                string[] flist = Directory.GetFiles(spath);
                foreach (string item in flist)
                {
                    File.Move(item, dpath + new FileInfo(item).Name);
                }
    

    将 D:\\Source & D:\\Destination\\ 分别替换为所需的源路径和目标路径。

    【讨论】:

    • 为什么是dynamic flist?我可以理解var flist,但dymanic 在这里似乎不合适,在这里你保证你会得到一个string[] 并且只能这样使用它。
    • 是的,你是对的。我对c#不太了解。我在 vb.net 中编写了程序。然后使用 Telerik Code Converter 将其转换为 C#。它将“暗淡”转换为“动态”。现已修复。
    • 如果您不确定答案,它可能更适合作为评论,而不是答案。 Telerik 的代码转换器在大多数情况下都可以正常工作,但偶尔会产生奇怪的或在某些情况下完全损坏的代码。
    • 但我测试了这段代码,它运行良好。如果需要,请自行测试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 2017-07-06
    相关资源
    最近更新 更多