【发布时间】:2018-10-31 00:42:28
【问题描述】:
我正在尝试将每个文件夹、子文件夹和文件放入路径之外的对象中。
此路径将包含许多顶级文件夹以及许多子文件夹和文件。
我需要分别处理每个顶级文件夹及其子文件夹和文件。
example
C:\temp\Folder1\SubFolder\SubFiles
C:\temp\Folder2\SubFiles\SubFolders\SubFiles
需要处理 Folder1 及其子目录并将其包含在一个对象中。和文件夹 2 相同。
这里有一些代码,因为流保持打开状态而被拒绝访问,如果我将流包装在 using 中,它会在我处理信息之前关闭。
private static IEnumerable<LocalFile> GetLocalFile(string source)
{
return Directory.GetDirectories(source)
.SelectMany(m =>
{
return Directory.EnumerateFileSystemEntries(m, "*", SearchOption.AllDirectories)
.Select(x =>
{
var relative = x.Substring(source.Length + 1);
var localFile = new LocalFile(relative,
() =>
{
return File.OpenRead(x);
});
return localFile;
});
});
}
public sealed class LocalFile
{
private readonly Func<Task<Stream>> openLocal;
public LocalFile(string relativePath, Func<Stream> openLocal)
{
if (openLocal == null)
{
throw new ArgumentNullException(nameof(openLocal));
}
this.RelativePath = relativePath ?? throw new ArgumentNullException(nameof(relativePath));
this.openLocal = () => Task.FromResult(openLocal());
}
public LocalFile(string relativePath, Func<Task<Stream>> openLocal)
{
this.RelativePath = relativePath ?? throw new ArgumentNullException(nameof(relativePath));
this.openLocal = openLocal ?? throw new ArgumentNullException(nameof(openLocal));
}
public string RelativePath { get; }
public Task<Stream> OpenLocal() => this.openLocal();
}
谢谢
【问题讨论】:
-
你能提供更多代码来说明这个问题吗?我真的不明白你在做什么或你在哪里遇到问题。此外,您可能需要选择更具描述性的问题标题。
-
LocalFile到底是什么? -
本地文件只是一个对象,包含两个属性,文件的相对路径和文件的流。
-
问题是,我需要单独处理每个顶级文件夹。函数 GetLocal() 抛出一个访问被拒绝的异常,这是因为文件流仍然是打开的,如果我将 file.openread() 包装在一个使用它抛出另一个异常不能访问一个关闭的流,如上所述。