C#集合被修改错误,从文件中读取乱码文本

本文关键字:读取 码文 文本 文件 集合 修改 错误 | 更新日期: 2023-09-27 18:25:04

我是C#的新手,被要求在我们的部署软件的插件中编写一个自定义任务,但我无法理解这一点。我只是试图将部署服务器上某个目录中的一些数据记录到输出日志中,但在收到关于"附加信息:集合已修改;枚举操作可能无法执行"的奇怪错误之前,我只记录了第一个文件(然后即使文本是乱码的,我认为它加载的字节不知何故是错误的)

这是我迄今为止的代码:

class Clense : AgentBasedActionBase
{
    public string dataPath { get; set; }
    protected override void Execute()
    {
        IFileOperationsExecuter agent = Context.Agent.GetService<IFileOperationsExecuter>();
        GetDirectoryEntryCommand get = new GetDirectoryEntryCommand() { Path = dataPath };
        GetDirectoryEntryResult result = agent.GetDirectoryEntry(get);
        DirectoryEntryInfo info = result.Entry;
        // info has directory information
        List<FileEntryInfo> myFiles = info.Files.ToList();
        foreach (FileEntryInfo file in myFiles)
        {
            Byte[] bytes = agent.ReadFileBytes(file.Path);
            String s = Encoding.Unicode.GetString(bytes);
            LogInformation(s);
            // myFiles.Remove(file); 
        }
    }
}

有人知道我能做些什么来解决这个问题吗?

更新

删除myFiles.Remove()修复了错误(我以为它会循环太多次,但没有),现在看起来每个文件只有一个日志条目,但消息仍然是乱码。有人知道为什么会发生这种事吗?

C#集合被修改错误,从文件中读取乱码文本

您可以反向迭代myFiles集合(这样在删除每个单独的文件时就不会损坏集合),也可以在完成迭代后简单地清除集合(这将实现相同的效果)。

您正在使用myFiles.Remote(文件);删除那一行(因为这是原因)。

在他的评论中,Blorgbeard在读取磁盘上文件的编码方面几乎可以肯定是正确的。请记住,Encoding.Unicode实际上是UTF16,这有点令人困惑,如果必须猜测的话,可能不是创建文件时使用的编码。

为了完整起见,我将添加BuildMaster惯用方法,使用IFileOperationsExecuter:上的ReadAllText()扩展方法来处理您的场景

protected override void Execute()
{
    var agent = this.Context.Agent.GetService<IFileOperationsExecuter>();
    var entry = agent.GetDirectoryEntry(new GetDirectoryEntryCommand() { Path = dataPath }).Entry;
    foreach(var file in entry.Files) 
    {
        string contents = agent.ReadAllText(file.Path);
        this.LogInformation(contents);
    }
}

ReadAllText()方法将在内部采用UTF8编码,但如果需要,会有一个重载接受不同的编码。